javascript - 正则表达式,分组常量字符串

标签 javascript regex

我正在使用这样的正则表达式:

/o?n?e?t?w?o?t?h?r?e?e?/

有没有办法做到这一点:

/(one)?(two)?(three)?/   // it doesn't work

我想用一个正则表达式替换单词“one”、“two”和“three”。

最佳答案

要用同一个词替换“one”、“two”或“three”,请使用 RegExp,用竖线分隔。还要为全局搜索和替换添加 g 标志。

例子:

var string = "one fellow, two hands, three legs";
string = string.replace(/(one|two|three)/g, "--$1--");
alert(string); //--one-- fellow, --two-- hands, --three-- legs

关于javascript - 正则表达式,分组常量字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8678249/

相关文章:

javascript - 在 discord.js 中发送文件缓冲区

javascript - 从数据库检索数据 - Laravel

javascript - AngularJS - 类型错误 : fn is not a function

regex - 为什么 VIM 有自己的正则表达式语法?

c++ - 正则表达式帮助,匹配产生额外的空格

python - 如何使用正向后行断言从单词 "named"之后的字符串中提取子字符串

用于替换的 Java 正则表达式 - 如何使其高效

javascript - 减少多个 if else 语句

javascript - jQuery .live ('click' ) 没有按预期工作

python - 匹配两个通配字符串的优雅方式