user1775888 user1775888 - 11 months ago 85
Javascript Question

regex replace only a part of the match

I want to replace only a part of the string of a regex pattern match. I found this answer but I don't get it...

How do I use substitution?

Example of what I want: keep the first slug digit, only replace others


unknown digit


unknown digit + "x"

Here is what I have so far:

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 Source

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


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.)