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 user1936584user19365843 Answers
Reset to default 2You 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
版权声明:本文标题:How can I replace string between two characters in javascript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742369944a2462036.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论