JavaScript replace
I'm doing something like:
<p>SQL</p&开发者_如何学Cgt;
<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.
replace is not a mutator method.
el.nodeValue = el.nodeValue.replace(/regex/,'something');
use it like so...
remember to google.. surprise!
try
p.childNodes[0].nodeValue = p.childNodes[0].nodeValue.replace(/sql/gi, 'VB.NET');
or
p.innerHTML = p.innerHTML.replace(/sql/gi, 'VB.NET');
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
.
Try this p.childNodes[0].nodeValue=p.childNodes[0].nodeValue.replace(/sql/gi, 'VB.NET');
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');
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, Find & replace jquery
精彩评论