user2300405
user2300405

Reputation: 11

How to replace as substring of a word using javascript regexp

I am trying to replace all occurrences of a regexp pattern with a new word. Currently I can only replace the coinsurance if it is an individual word that separated by space " ", but I would like to replace all of them even if they are in the middle of a word. Here is an example:

for string: abc:target12 target12 cdtarget23 target

I would like to replace all the occurrences of target[0-9]{2} with "ok", so after the replacement, the new string would be like: abc:ok ok cdok target

Thanks!

Upvotes: 1

Views: 214

Answers (2)

anubhava
anubhava

Reputation: 785276

Use replace like this:

var repl = str.replace(/target\d{2}/g, 'ok');

Live Demo: http://ideone.com/hew6oa

Upvotes: 1

Jason Sperske
Jason Sperske

Reputation: 30436

I think you are missing the g (Global) at the end of your regex (demo):

alert("abc:target12 target12 cdtarget23 target".replace(/target[0-9]{2}/g, 'ok'))

Upvotes: 1

Related Questions