简体   繁体   中英

Regular Expression text insertion in javascript

I have some string that could be on a URL.. ala.. I can "get the name/value" etc.. that is not the issue. The issue is that given some test I need to "insert" additional characters in the value. so:

var someValue = "yes_maybe_next_year"

If I get a string with "_maybe" in it, I would insert my additional chars after it, ala. so it would become:

var charsToInsert = "_no";
var someValue = "yes_maybe_next_year";
var newValue = "yes_maybe_no_next_year";

Here is the rub. I might not get "maybe" in there. So I need to insert "_no" after "yes". Here is a second rub. The string might contain chars that are different than "next_year".

var someValue = "yes_sometime_later";

So, in truth: I need to be able to insert via regex something like.

var regex = /^(yes_)(maybe_)(\w*)?/

I'm actually at a loss on how to do this.

So, if "maybe_" exists, I'll put "no" after it, else "no" goes after "yes_".

Here is one possible solution:

var newValue = someValue.replace(/yes_(maybe_)?/, "$&no_");

// "yes_maybe_next_year" --> "yes_maybe_no_next_year"
// "yes_sometime_later"  --> "yes_no_sometime_later"

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