最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

replace - Finding & Replacing a Word within a Div Using Good Ole JavaScript - Stack Overflow

programmeradmin2浏览0评论

I know this is quite easy to do in jQuery, but I am trying to do it in JavaScript.

I have this:

window.addEventListener('load', function() {

        function replaceName() {
        var oldText= "Mobile";
        var newText = "Stackoverflow";
        var oldString= document.getElementById('replace').innerHTML;
        var newString = oldString.replace(/oldText/g, newText);
        document.getElementById('replace').innerHTML = newString;
        }

        replaceName();

}, false);

Not sure what I'm doing wrong? Any thoughts?

Thanks

I know this is quite easy to do in jQuery, but I am trying to do it in JavaScript.

I have this:

window.addEventListener('load', function() {

        function replaceName() {
        var oldText= "Mobile";
        var newText = "Stackoverflow";
        var oldString= document.getElementById('replace').innerHTML;
        var newString = oldString.replace(/oldText/g, newText);
        document.getElementById('replace').innerHTML = newString;
        }

        replaceName();

}, false);

Not sure what I'm doing wrong? Any thoughts?

Thanks

Share Improve this question asked May 30, 2011 at 23:29 YahreenYahreen 1792 silver badges10 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 7

Currently, you are doing it the error prone way.

Error prone because you will lose event handlers as well as replacing things you may not want to replace. What if the search term was 'a'? Would you want all a elements turning into whatever the replace string is?

Also, you are needlessly serialising the HTML from the DOM of which needs to be reparsed when you set it again.

The correct way to do this is to iterate over the text nodes only.

var replaceText = function replaceText(element, search, replace) {
    var nodes = element.childNodes;

    for (var i = 0, length = nodes.length; i < length; i++) {

        var node = nodes[i];

        if (node.childNodes.length) {
            replaceText(node, search, replace);
            continue;
        }

        if (node.nodeType != 3) {
            continue;
        }

        node.data = node.data.replace(new RegExp(search, 'g'), replace);
    }

}

jsFiddle.

The problem is here:

var newString = oldString.replace(/oldText/g, newText);

It's actually searching for oldText and not "Mobile"

As kb said, you can solve this by:

var newString = oldString.replace(new RegExp(oldText, "g"), newText);

For the sake of providing an answer that doesn't use eval (repeat after me: don't use eval!), try this line:

var newString = oldString.replace(new RegExp(oldText, "g"), newText);

Where previously you had /pattern/flags, now you have new RegExp(pattern, flags)

Just set

var oldText = /Mobile/g
发布评论

评论列表(0)

  1. 暂无评论