0

I need to replace the text between two parentheses using Regex in Javascript. For example:

var x = "I need to go (now)";

I need to replace 'now' with 'tomorrow'. I tried this, but it didn't work:

x.replace(/\(now)\b/g, 'tomorrow');
6
  • 1
    Use x = x.replace('(now)', '(tomorrow)'); Commented Aug 6, 2015 at 15:25
  • Welcome to SO. Please search for your question first. Also read the help center Commented Aug 6, 2015 at 15:26
  • You don't need Regex for such trivial problem. Use String's methods, as @anubhava suggested Commented Aug 6, 2015 at 15:27
  • 1
    @anubhava does that replace all occurrences? I think it replaces only one Commented Aug 6, 2015 at 15:29
  • 1
    That is correct. Only one Commented Aug 6, 2015 at 15:29

1 Answer 1

3
"I need to know (now)".replace(/\(now\)/g, 'tomorrow');

You don't need the \b and you need to escape the second ).

Sign up to request clarification or add additional context in comments.

2 Comments

Does that replace all occurrences?
The code in my post will replace all occurrences because of the g flag at the end of the regex. Remove it to only replace the first occurrence.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.