Javascript 替换正则表达式任何字符



我正在尝试替换类似"?order=height"之类的东西,我知道它可以很容易地像这样完成:

data = 'height'
x = '?order=' + data
x.replace('?order=' + data, '')

但问题是问号有时可以是和号。我真正想做的是空白第一个字符是 & 号还是问号,所以基本上是否

?order=height
&order=height

可以设为空字符串

x.replace(/[&?]order=height/, '')

如果数据是字符串变量

x.replace(/[&?]order=([^&=]+)/, '')

对该.replace(/[?&]order=height/, '')使用正则表达式

[?&] 表示此列表中的任何字符。

/是开始和结束分隔符。

请注意,模式不是用'"括起来的字符串。

这就是你可以做到的。创建RegExp对象

"[&?]order=" + match

并使用String.prototype.replace替换为"

function replace(match, str) {
   regex = new RegExp("[&?]order=" + match,"g")
  return str.replace(regex, "")
}
console.log(replace("height", "Yo &order=height Yo"))
console.log(replace("weight", "Yo ?order=weight Yo"))
console.log(replace("age", "Yo ?order=age Yo"))

相关内容

最新更新