admin管理员组

文章数量:1335349

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';

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';

Share Improve this question asked Mar 27, 2015 at 8:07 user1936584user1936584
Add a ment  | 

3 Answers 3

Reset to default 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.

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 '

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');

本文标签: How can I replace string between two characters in javascriptStack Overflow