简体   繁体   中英

Javascript replace regex any character

I am trying to replace something like '?order=height' and I know it can be easily done like this:

data = 'height'

x = '?order=' + data

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

But the problem is that question mark can sometimes be ampersand.. What I really wish to do is make blank whether the first character is ampersand or question mark so basically whether

?order=height
&order=height

can be made a blank string

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

如果数据是字符串变量

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

Use regex for that .replace(/[?&]order=height/, '')

[?&] means any character from this list.

/ is start and end delimiter.

Please note that pattern is not enclosed as string with ' or " .

This is how you may do it. Create a RegExp object with

"[&?]order=" + match

and replace with "" using 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")) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM