0

Just curious. what are the differences between?

var a=text.replace(/(Nullam|ligula|in)/ig,'`<b>$1</b>`');

with

var string = "Nullam|lingula|in";  
var pattern = new RegExp (string, "ig");    
var a=text.replace(pattern ,'`<b>$1</b>`');

This should gives out the same result, but it doesn't. Any thoughts?

Thank you

1
  • If you wrote $0 instead of $1 in your second example, then you'd get the same result in both. Actually, you'd also get that if you used $0 in the first example. Commented Aug 1, 2011 at 20:15

1 Answer 1

3

You're missing parens in your later statement, so there are no captures. And the flag is gi, not ig (although I'm not sure if this makes any difference)

var reString = "(Nullam|lingula|in)"; var pattern = new RegExp (reString, "gi");
Sign up to request clarification or add additional context in comments.

5 Comments

For example, when the first technique found one of words, it will make it bold, and wont' replace the word. Meanwhile, when the second one found one of words, it will make it bold and literally it will replace the word to "$1". That is what comes out from my experiment. What I am trying to achieve is to just make the word bold without literally replace the word. Is this possible? (with dynamic keywords)
Yes, and that's because you're missing the parens which creates a capture group.
Following your suggestion. I tried and cannot get it to work. Here are my experiments: First technique jsfiddle.net/oceog/q8S7E AND Second technique: jsfiddle.net/UyWTf/1
You're not loading jQuery in the fiddle. This works in chrome: jsfiddle.net/UyWTf/2
Interesting. It works in Chrome. Somehow after clearing all the caches and etc, it works now in Firefox. Anyway, I am still learning about RegExp. Thank you very much for your help. I really appreciate it.

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.