Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

/09/small_image/09x/ > /09/thumbnail/
1st: unknown digit
2nd: "small_image"
3rd: 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');
}
like image 522
user1775888 Avatar asked Oct 10 '16 03:10

user1775888


People also ask

How do you substitute in regex?

To perform a substitution, you use the Replace method of the Regex class, instead of the Match method that we've seen in earlier articles. This method is similar to Match, except that it includes an extra string parameter to receive the replacement value.

What is $1 in regex replace?

For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string).

What does regex 0 * 1 * 0 * 1 * Mean?

Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1.


2 Answers

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

like image 196
nnnnnn Avatar answered Oct 14 '22 15:10

nnnnnn


Go with

var regexPattern = /(\/\d+\/)small\_image\/\d*x/;

and

str = str.replace(regexPattern, '$1thumbnail');

First, you were missing the +. Because 09 are two digits, you need the regexp to match one or more digits (\ḑ would be exactly one). This is accomplished by \d+
Second, everything you match is being removed at first. To get the /09/ part back afterwards, you have to remember it by putting it into brackets in the regexp (...) and afterwards reference it in the replacement via $1
One could as well create other groups and reference them by $2,$3 ...

like image 30
Syntac Avatar answered Oct 14 '22 15:10

Syntac