$1 in regular expression javascript

Carlos

when I use var j= new RegExp('('+val+')','gi') then $1 works fine. but when I am using it without bracket then it is not working. So I want to know why brackets is necessary and does $1 hold the value which have to be replaced?

var val='city'
var j= new RegExp('('+val+')','gi')
console.log(j)
$('div').html(function(i,val){
return val.replace(j,'<span>$1</span>')
})
Barmar

$n is replaced by the part of the string that matched the nth capture group in the regexp. Capture groups are the parts of the regular expression in parentheses. If you don't have any parentheses, there are no capture groups, so $1 won't be replaced with anything.

If you want the match for the entire regexp, use $&.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related