views:

76

answers:

6
+1  Q: 

JavaScript replace

I'm doing something like:

<p>SQL</p>
<p>sql</p>
<p>sQl</p>
<p>SqL</p>
<script type="text/javascript">
var ps = document.getElementsByTagName('p');

for(var i = 0; i < ps.length; i++) {
 var p = ps[i];
 p.childNodes[0].nodeValue.replace(/sql/gi, 'VB.NET');
 p = null;
}
</script>

But it's not replacing the text. What's wrong? Thank you.

+4  A: 

replace is not a mutator method.

el.nodeValue = el.nodeValue.replace(/regex/,'something');

use it like so...

remember to google.. surprise!

meder
ok, thank you!problem solved!
thomas
@thomas: Hey, your question is already rank 4 over at Google with meder's search terms ;-)
Boldewyn
A: 

try

p.childNodes[0].nodeValue = p.childNodes[0].nodeValue.replace(/sql/gi, 'VB.NET');

or

p.innerHTML = p.innerHTML.replace(/sql/gi, 'VB.NET');
oezi
Caution with use of innerHTML as it's still not officially part of the dom (although it should).
gnome
A: 

You are not assigning the replacement back into the p element.

Also remember that alert is your friend. See what's in p.childNodes[0].nodeValue.

Jason McCreary
A: 

Try this p.childNodes[0].nodeValue=p.childNodes[0].nodeValue.replace(/sql/gi, 'VB.NET');

Dharma
A: 

I believe replace, here, is simply returning the value (it's been a while).

Have you tried:

p.childNodes[0].nodeValue = p.childNodes[0].nodeValue.replace(/sql/gi, 'VB.NET');
Christopher W. Allen-Poole
A: 

I would pull that out into a function in the documents head, then call the method before the closing body tag. This will ensure that the document logs before the js executes:

// head
<script type='text/javasript'>
function changeText() {
var ps = document.getElementsByTagName('p');
for(var i = 0; i<ps.length; i++) {
var node = ps[i].childNodes[0].nodeValue.toLowerCase();
node = node.replace('sql', 'VB.NET');
ps[i].childeNodes[0].nodeValue = node;
}
}
</script>
// Before the closing body tag
<script type='text/javascript'>changeText();</script>

You could also using jQuery, here's a find / replace approach, http://stackoverflow.com/questions/233922/find-replace-jquery

gnome