简体   繁体   中英

regexp replace with forward slash

I can't understand for the life of me which this isn't replacing normal/ in the str. I imagine there is a way to escape it but everything i've tried doesn't seem to work.

http://jsfiddle.net/KU6U5/

str = 'http://www.foobar.com/foo/normal/a.jpg';

var usedPreSizeRangeRegExp = new RegExp("(tn/tn_|tn_med/|normal/|lrg/lrg_|'original/)$");

strd = str.replace(usedPreSizeRangeRegExp, "");
alert(strd);

normal/ will never match because you have $ at the end of your regular expression which matches the end of the string. Since normal/ doesn't occur near the end at all, this will never match.

Removing the $ and changing the regular expression to:

new RegExp("(tn/tn_|tn_med/|normal/|lrg/lrg_|'original/)")

does work.

Fiddle .

normal/ isn't located at the end of the string and the $ in your regex requires it.

Try

var usedPreSizeRangeRegExp = new RegExp("(tn/tn_|tn_med/|normal/|lrg/lrg_|'original/)");

RegexPal demo

You can escape / with a \\ so you would get \\/ . You added a $ at the end, which means, that only match everything at the end of the string, but the string doesn't end with any of the options, so there wont be any matches.

var str = 'http://www.foobar.com/foo/normal/a.jpg';
var strd = str.replace(/(tn\/tn_|tn_med\/|normal\/|lrg\/lrg_|'original\/)/, "");

Try this:

str = 'http://www.foobar.com/foo/normal/a.jpg';

var usedPreSizeRangeRegExp = new RegExp("(tn\/tn_|tn_med\/|normal\/|lrg\/lrg_|'original\/)");

strd = str.replace(usedPreSizeRangeRegExp, "");
alert(strd);

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