Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do u replace a string that's not inside a specific div?

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

like image 787
Squirrl Avatar asked Jan 27 '14 09:01

Squirrl


People also ask

How to search and replace a substring with a new one?

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.

How to replace a string in Java?

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"

How do you replace a string in a char sequence?

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.

How do you replace a string in regexp?

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.


2 Answers

You can use the .contents() method and replace nodeValue properties of the textNodes.

$('#content').contents().each(function(){
    if (this.nodeType === 3)
        this.nodeValue = this.nodeValue.replace('ok', 'cool');
});

http://jsfiddle.net/82tmP/

like image 79
undefined Avatar answered Oct 25 '22 22:10

undefined


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);
like image 35
A1rPun Avatar answered Oct 26 '22 00:10

A1rPun