JavaScript Replace with Reference to Matched Group

Javascript replace with reference to matched group?

"hello _there_".replace(/_(.*?)_/, function(a, b){
return '<div>' + b + '</div>';
})

Oh, or you could also:

"hello _there_".replace(/_(.*?)_/, "<div>$1</div>")

Javascript replace matched group

You can capture the parts you don't want to replace and include them in the replacement string with $ followed by the group number:

s.replace(/(\w)\n(\w)/g, "$1<br />\n$2");

See this section in the MDN docs for more info on referring to parts of the input string in your replacement string.

How to replace captured groups only?

A solution is to add captures for the preceding and following text:

str.replace(/(.*name="\w+)(\d+)(\w+".*)/, "$1!NEW_ID!$3")

Explanation

The parentheses are used to create "groups", which then get assigned a base-1 index, accessible in a replace with a $.

  • the first word (\w+) is in a group, and becomes $1
  • the middle part (\d+) is the second group (but gets ignored in the replace)
  • the third group (\w+".*) becomes $3

So when you give the replace string of "$1!new_ID!$3", the $1 and $3 are replaced automagically with the first group and third group, allowing the 2nd group to be replaced with the new string, maintaining the text surrounding it.

Javascript replace character in regular expression in matched group

You may use this lambda approach in .replace:

const s = 'test-string-foo-bar-baz-another-foo-bar-baz';

var repl = s.replace(/(foo-)(\w+)(-baz)/g,
(m, g1, g2, g3) => g1 + g2 + g2.replace(/r/g, "t") + g3);

console.log(repl);

replace javascript regexp matched group with a dollar sign

"1.99 or 4.89".replace(/(\d\.\d\d)/g, "$$$1")
// => "$1.99 or $4.89"

Since $ is special in replacement string, it must be escaped into $$ for a literal $. It is not escaped using the \ character, which is a general string escape mechanism, and processed before the string reaches replace (i.e. if you say "\$", it becomes "$" before being passed as an argument, so replace never sees the escaping).

How to replace RegExp capture groups?

The problem is caused by the two layers of interpretation that the backslashes undergo. First you have JavaScript's string literal syntax, which uses backslashes to escape characters. When you have a string like

'(\'|\"|\_|\[)(A)(\'|\"|\_|\])'

in your code, the actual contents are:

('|"|_|[)(A)('|"|_|])

This is then parsed by the RegExp constructor, which treats [)(A)('|"|_|] as a single character class equivalent to [A'"_()|].

To preserve a backslash so the regexp engine can see it, you have to put two backslashes in your string.

You can also use character classes to simplify your code a bit:

var regex = new RegExp('([\'"_[])A([\'"_\\]])', 'g')var string = ' [A] _A_ "A" \'A\' A BAB "B" 'console.log(string.replace(regex, '$1X$2'));

Dynamically replace data based on matched RegEx JavaScript

Luckily, replace() allows to use a callback:

matchesMessage = template.replace(
/\{\{(.+?)\}\}/g,
(match, tag) => data[tag.trim()]
);

console.log(matchesMessage);
// "There are six matches for the category shoes."

Replace capture group of dynamic size

You can use the sticky flag y (but Internet Explorer doesn't support it):

s = s.replace(/(^https?:\/\/.*?\/path1\/?|(?!^))./gy, '$1*')

But the simplest (and that is supported everywhere), is to use a function as replacement parameter.

s = s.replace(/^(https?:\/\/.+\/path1\/?)(.*)/, function (_, m1, m2) {
return m1 + '*'.repeat(m2.length);
});

For the second case, you can simply check if there's an @ after the current position:

s = s.replace(/.(?=.*@)/g, '*');


Related Topics



Leave a reply



Submit