4

I am having an issue which I cannot find documented anywhere, i see a regex method however that is using a direct string rather than string within a variable. This is my code:

var src = getQueryVariable("srcStr");

            if(src != false){
               $(".entry-content").html($(".entry-content")
              .html().replace(/src/g, "<span style='background-color:#f2e128;'>" 
              + src + "</span>"));

}

This gets a url variable (srcStr) and searches a body of text within .entry-content for the string stored in the var src.

The problem code is here: replace(/src/g

Is there a solution?

1
  • I might not understand what you're trying to say, but anytime you see a method that asks for a string, you can use a variable that's storing a string. Commented Dec 3, 2012 at 12:51

1 Answer 1

9

You are searching for the pattern that is literally "src." You need to use the RegExp class if you want to use variables in patterns:

pattern = new RegExp(src, 'g');
$(".entry-content")...html().replace(pattern, replacement);
Sign up to request clarification or add additional context in comments.

2 Comments

This advice is flawed. Don't recommend building regular expressions from strings without also saying that the string must be regex-quoted first.
Just a note of caution: if the src string contains special chars (mainly ``) you'll need to escape that char

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.