Regex replace only part of the match

I want to replace only part of the string matching the regular expression pattern. I found this answer , but I do not understand ... How to use substitution?

An example of what I want: save the first digit of the bullet, replace the others

/09/small_image/09x/> /09/thumbnail/
1st: unknown digit
2nd: "small_image"
Third:unknown digit + "x"

Here is what I still have:

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');
}
+4
source share
2 answers

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

Explanation:

, , $1 - $1 . , (\/\d+\/) , , .

( , .)

+6

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

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

, +. 09 - , , (\ḑ ). \d+
, , , . /09/ , , regexp (... ), $1
$2, $3...

0

Source: https://habr.com/ru/post/1657232/


All Articles