简体   繁体   中英

JavaScript string replace() not working when replacing variable

I'm trying to create a JavaScript script for highlighting certain text on a page. Right now I'm having issues trying to replace text (from the body html) with other text. I want to replace all instances of each item in the array highlights with some other text.

The code that I'm using is:

    var responseText = server.responseText;
    var highlights = responseText.split("\n");
    var text = document.body.innerHTML;

    for (i in highlights) {
        if (highlights[i].length > 1) {
            var exp = new RegExp(highlights[i], "g");
            console.log(exp);
            console.log(highlights[i]);
            text = text.replace(exp, "XXXXXXXXXXX");
        }
    }

    document.body.innerHTML = text;

Currently, I am getting the correct value printouts for highlights[i] and I think I am for the regular expression exp ; if highlights[i] is 'Remember', then the printout I'm getting for exp is '/Remember/g' (without the quotation marks) -- but it's not replacing the word 'Remember' on the page. 'And if I replace highlights[i] in the new RegExp() with simply the string "Remember" it works correctly. Any ideas on what's wrong?

EDIT: I solved the problem! When creating the RegExp() I passed in highlights[i].trim() instead of just highlights[i] to get rid of whitespace at the beginning/end and it appears to be working now.

There is some problem with your multiline server.responseText . I replaced the input with spaces instead of newlines, and all the replacements work fine :

http://jsfiddle.net/XTdgJ/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM