user1775888 user1775888 - 1 month ago 15
Javascript Question

regex replace a part substitution

I want to replace a part string of match regex pattern, I found http://stackoverflow.com/a/8995358/1775888 this answer but I don't get it ...

how to use substitution

example keep first slug digit only replace others

/09/small_image/09x/
>
/09/thumbnail/


1st:
unknown digit


2nd:
small_image


3rd:
unknown digit + x


var regexPattern = /\/\d\/small\_image\/\d*x/;
var regexPattern = /\/\d\/(small\_image\/\d*x)$1/; ??

var result = regexPattern.test(str);
if (result) {
str = str.replace(regexPattern, 'thumbnail');
}

Answer

var input = "/09/small_image/09x/";
var output = input.replace(/(\/\d+\/)small_image\/\d*x/, "$1thumbnail");
console.log(output);

Explanation:

Put the part you want to keep in parentheses, then refer to that as $1 in the replacement string - don't put $1 in your regex. So (\/\d+\/) means to match a forward slash followed by one or more digits, followed by another forward slash.

(Note that you don't need to escape underscores in a regex.)