0

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_".

1
  • If you use conditions, good practice to do it in 2 steps: if .. else. Regex is pretty expensive in your case. Its seems good to do it with 1 row but ... :) Commented Feb 20, 2013 at 9:04

1 Answer 1

3

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"
Sign up to request clarification or add additional context in comments.

2 Comments

yeah, after goofing around, I came up with this: .replace(/^(yes_)(maybe_)?/, "$1$2no_") ---> what does your $& do?
@VisionN - so in this case it would be short for my "$1$2"?

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.