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?

3
  • Looking for literal texts using a regex you should consider escaping the strings. Commented Jul 10, 2018 at 7: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...) Commented Jul 10, 2018 at 7:41
  • @T.J.Crowder that makes a lot of sense, it works now Commented Jul 10, 2018 at 7:42

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.