我正在寻找一种方法来从另一个子字符串中删除大括号内的任何子字符串。
例如:
- 如果我有字符串
“The cat is {not} mine”
,我想要一个返回“The cat is mine”的函数;
- 如果我有
“玻璃被狗打破了”
,我想要一个返回“玻璃被打破了”
的函数
我读到可以在 replace
函数中使用正则表达式,但我不知道如何使用它。
最佳答案
这有效:
var s="The {yellow} cat is {not} mine";
s.replace(/\s?\{[^}]+\}/g, ''); // "The cat is mine"
正则表达式允许可选的前导空格 s?
,然后找到左大括号 \{
,然后搜索组 []+
中的多个字符这不是右大括号 ^}
- 直到文字结束 curl }
.
所有操作均通过 g
进行操作多次替换的全局标志。
全部替换为 ""
.
<[this stuff]>
由 <[]>
分隔:
var s = "The <[yellow]> cat is <[not]> mine";
s = s.replace(/\s*<\[[^\]\>]*\]>/g, "");
console.log( s ); // "The cat is mine"
关于javascript - 正则表达式删除大括号中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32172541/