I have this html:
<div id="content">This following word is not <span id="notOk">ok</span> but all the other words are ok</div>
And using this jquery I'm trying to replace the word ok
with cool
, as long as the word ok
is not inside the span #notOk
.
var content = $('#content').html()
content = content.replace('ok', 'cool');
$('#content').html(content)
I also want to preserve the sentence and not move any words around, which is what happened when I tried. I guess I'm looking for something like dontGetElementByID('').?
FIDDLE
Sometimes, you want to search and replace a substring with a new one in a column e.g., change a dead link to a new one, rename an obsolete product to the new name, etc. SQL provides a very helpful string function called REPLACE that allows you to replace all occurrences of a substring in a string with a new substring.
There are two types of replace () methods in Java String class. The second replace () method is added since JDK 1.5. NullPointerException: if the replacement or target is equal to null. FileName: ReplaceExample1.java FileName: ReplaceExample2.java String replaceString=s1.replace ("is","was");//replaces all occurrences of "is" to "was"
Java String replace () The java string replace () method returns a string replacing all the old char or CharSequence to new char or CharSequence. Since JDK 1.5, a new replace () method is introduced, allowing you to replace a sequence of char values.
regexp − A RegExp object. The match is replaced by the return value of parameter #2. substr − A String that is to be replaced by newSubStr. newSubStr − The String that replaces the substring received from parameter #1. function − A function to be invoked to create the new substring. It simply returns a new changed string.
You can use the .contents()
method and replace nodeValue
properties of the textNode
s.
$('#content').contents().each(function(){
if (this.nodeType === 3)
this.nodeValue = this.nodeValue.replace('ok', 'cool');
});
http://jsfiddle.net/82tmP/
Replace the value just like you did.. then replace it back :)
var content = $('#content').html()
content = content.replace('ok', 'cool');
$('#content').html(content);
content = $('#notOk').html();
content = content.replace('cool', 'ok');
$('#notOk').html(content);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With