3

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>')
})
Jitender
  • 7,593
  • 30
  • 104
  • 210

3 Answers3

6

$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 $&.

Barmar
  • 741,623
  • 53
  • 500
  • 612
1

By brackets, do you mean paranthesis?

If so, paranthesis denote a capture group in regex, which means that the content inside is captured.

If you need help accessing captured groups you can look at this answer, which explains it quite thoroughly.

Community
  • 1
  • 1
Robin
  • 1,251
  • 11
  • 18
0

Parentheses are used to form capturing groups in regular expressions. See more details here: http://www.regular-expressions.info/refcapture.html

Note that in order to match the parentheses, you have to escape them.

Silviu Burcea
  • 5,103
  • 1
  • 29
  • 43