0

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.

11
  • 5
    Don't use for ..in to iterate through arrays, use a regular for loop. Commented Sep 10, 2012 at 6:42
  • What is wrong with /Remember/g ? Commented Sep 10, 2012 at 6:42
  • 1
    Can you reproduce this behaviour with a live demo? JS Fiddle, or similar? Commented Sep 10, 2012 at 6:52
  • 1
    @Musa What's wrong with for...in? Is there any reason why that would be messing up the replace()? Commented Sep 10, 2012 at 6:52
  • str.replace will replace only the first element of a string if you do not pass a regular 'Regular expression' :) Commented Sep 10, 2012 at 6:53

1 Answer 1

2

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/

Sign up to request clarification or add additional context in comments.

2 Comments

Ok, so I called trim() on each line (to clean them up) before creating the regular expression and it appears to be working now. I thought that I'd already tried it earlier, but I guess not.
@scae newlines are usually hard to detect in console as well !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.