2

How can I replace a string between two given characters in javascript?

var myString = '(text) other text';

I thought of something like this, using regex but I don't think it's the right syntax.

myString = myString.replace('(.*)', 'replace');

My expected results is myString = 'replace other text';

3 Answers 3

2

You can match just bracketed text and replace that:

myString.replace(/\(.*\)/g, 'replace');

or, if you only ever want to match (text), use

myString.replace('(text)', 'replace');

Your original wasn't working because you used a string instead of a regex; you were literally looking for the substring "(.*)" within your string.

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

Comments

2

The answer of choice is fine with one instance of (text). It won't work with something like '(text) other text, and (more text)'. In that case, use:

var str = '(text) other text, and (more text)';
var strCleaned = str.replace(/\(.*?[^\)]\)/g, '');
//=> strCleaned value: 'other text, and '

Comments

0

You are doing a text replacement where the exact text is searched for. You can use a regex for searching a pattern

myString = myString.replace(/\(.*\)/, 'replace');

1 Comment

This won't work with multiple instances of the search term: try it using the string '(text) other text, and (more text)'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.