Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript String replace - How do you use matched variables in the replacement string?

How do you use the matched variables in the pattern in the replacement string?

var regexp = new RegExp('needle', 'ig');
str.replace(regexp, '<span class="marked">//1</span>')
like image 684
clarkk Avatar asked Aug 09 '11 08:08

clarkk


People also ask

How does string replace work in JavaScript?

replace() The replace() method returns a new string with one, some, or all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function called for each match. If pattern is a string, only the first occurrence will be replaced.

How do you use the Replace function in string?

The replace() method searches a string for a value or a regular expression. The replace() method returns a new string with the value(s) replaced. The replace() method does not change the original string.

How do you match variables in JavaScript?

To use variable in string match with JavaScript, we can use the RegExp constructor to create our regex. const re = new RegExp(vowels, "gi"); The first argument is the regex pattern string and the 2nd argument is the string with the flags. g means we return all matches and i means we search in a case-insensitive manner.

How do you get the matching characters in a string in JS?

JavaScript match() Function. The string. match() is an inbuilt function in JavaScript used to search a string for a match against any regular expression. If the match is found, then this will return the match as an array.


2 Answers

try

var regexp = new RegExp(something, 'ig');
str.replace(regexp, '<span class="marked">$&</span>')

References:

  • A table specifying the format of different tokens to be used into the replacement string

  • An example on how to switch two words into a string

like image 137
Eineki Avatar answered Oct 25 '22 23:10

Eineki


The correct way to use backreferences in JavaScript is via $1...$9.

To make your example work:

var regexp = new RegExp(something, 'ig');
var result = str.replace(regexp, '<span class="marked">$1</span>');

More information is available here: http://www.regular-expressions.info/javascript.html#replace

like image 32
OverZealous Avatar answered Oct 25 '22 23:10

OverZealous