简体   繁体   English

替换字符串中的单词和字符

[英]Replace word and characters in string

I'm in the midst of figuring out the RegExp function capabilities and trying to create this string: 我正在弄清楚RegExp函数的功能并尝试创建此字符串:

api/seaarch/redirect/complete/127879/2013-11-27/4-12-2013/7/2/0/0/LGW/null

from this: 由此:

/api/search/redirect/complete/127879/2013-11-27/4-12-2013/7/2/0/0/undefined/undefined/undefined/undefined/undefined/undefined/undefined/undefined/undefined/^^undefined^undefined^undefined^undefined^undefined/undefined^undefined^undefined^undefined^undefined^undefined^undefined/undefined^undefined^undefined^undefined^undefined^undefined^undefined/undefined^undefined^undefined^undefined^undefined^undefined^undefined/LGW/null

I know \\bundefined\\b\\^ removes 'undefined^' and undefined\\b\\/ removes 'undefined/' but how do i combine these together? 我知道\\bundefined\\b\\^删除了'undefined ^'和undefined\\b\\/删除了'undefined /',但是我如何将它们组合在一起?

In this case, since the ^ or / follow the undefined in the same place, you can use a character class: 在这种情况下,由于^/undefined位置跟在undefined位置,因此可以使用字符类:

str = str.replace(/\bundefined[/^]+/g, '');

Note: ^ is special both inside and outside of character classes, but in different ways. 注意: ^在字符类的内部和外部都是特殊的,但是以不同的方式。 Inside a character class ( [...] ), it's only special if it's the first character, hence my not making it the first char above. 字符类( [...] )中,只有它是第一个字符才是特殊的,因此我没有将其作为上面的第一个字符。

Also note the + at the end, saying "one or more " of the ^ or / . 还要注意末尾的+ ,表示^/ “一个或多个 ”。 Without that, since there are a couple of double ^^ , you end up with ^ in the result. 否则,由于有几个double ^^ ,结果将以^结束。

If you want to be a bit paranoid (and I admit I probably would be), you could escape the / within the character class. 如果您想变得有点偏执(我承认我可能会这样),则可以在字符类中转义/ For me it works if you don't, with Chrome's implementation, but trying to follow the pattern definition in the spec is...tiresome...so I honestly don't know if there's any implementation out there that would try to end the expression as of the / in the character class. 对我来说,如果您不使用Chrome的实现,它就可以工作,但是尝试遵循规范中的模式定义会很麻烦……所以,老实说,我不知道是否有任何实现会尝试结束字符类中以/开头的表达式。 So with the escape: 因此,使用转义符:

str = str.replace(/\bundefined[\/^]+/g, '');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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