0

I'm trying to return how many times the string s.t() was found in a string, but I can't get the correct regex for this...

For example

var string = 'function(test) {s.t(); s.t(dsabf); s.t();}'
var re = new RegExp('s\.t\(\)', "g");
return re;

should return an array of 2 elements ['s.t()', 's.t()'] but instead it has 3 elements ['s.t', 's.t', 's.t']

I've also tried with ^s\t\(\)$ but this returns no match...

How can I fix my regex in order to make this work as expected?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Valip
  • 4,440
  • 19
  • 79
  • 150
  • Looking for literal texts using a regex you should consider [escaping the strings](https://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript). – Wiktor Stribiżew Jul 10 '18 at 07:40
  • 1
    The backslashes in the string you're passing `new RegExp` don't end up being backslashes in the pattern, because they're processed by the string literal. Either use a regex literal: `var re = /s\.t\(\)/g;` or escape them so they're really backslashes: `var re = new RegExp('s\\.t\\(\\)', "g");` (You don't actually have to escape the `)` when it's not in a group, but...) – T.J. Crowder Jul 10 '18 at 07:41
  • @T.J.Crowder that makes a lot of sense, it works now – Valip Jul 10 '18 at 07:42

0 Answers0