简体   繁体   中英

Replace word and characters in string

I'm in the midst of figuring out the RegExp function capabilities and trying to create this string:

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?

In this case, since the ^ or / follow the undefined in the same place, you can use a character class:

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.

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. So with the escape:

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

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