简体   繁体   中英

Replace last occurrence of word in string jQuery

Hello I'm trying to replace the last occurrence of foo in the string code . It's worth mentioning that foo is a variable containing a random string - this needs to be parsed into the regex.

$(target).html(code.replace(foo, replaced_text));

Maybe using new RegExp() in some shape or form would be a good port of call - although injecting foo gets unexpected results.

Any advice would be appreciated.

Use the greediness of *

$(target).html(code.replace(/(.*)foo/, "$1" + replaced_text));

or

If foo is a variable.

$(target).html(code.replace(new RegExp("(.*)" + foo), "$1" + replaced_text));

If the variable foo variable contain special characters.

> var foo = "$foo$"
> new RegExp("(.*)" + foo.replace(/(\W)/g, "\\$1"))
/(.*)\$foo\$/

Simply ensure that no other foo s follow using negative lookahead :

$(target).html(code.replace(/foo(?!.*foo)/, replaced_text));

Or given that foo is a variable:

$(target).html(code.replace(new RegExp(foo + "(?!.*" + foo + ")"), replaced_text));

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