0

I'm trying ti use match() in order to parse through some text and return the amount of times the text shows up. I'm doing this by using a global match and then calling length on the array that is created from the match. Instead, I'm just getting a array with a single element.

$('button').click(function () {
    checkword = "/" + specialWord + "/g";
    finalAnswer = userText.match(specialWord);
    console.log(finalAnswer);
    $('#answer').html(finalAnswer + '<br>' + finalAnswer.length);
    return finalAnswer;
});

For example my search for 'is' in "this is" should return an array with a length of two, correct?

Fiddle: http://jsfiddle.net/

Josh
  • 61
  • 6
  • Related: [How to count string occurrence in string?](http://stackoverflow.com/questions/4009756/how-to-count-string-occurrence-in-string) – Ja͢ck Nov 21 '14 at 02:28
  • If `specialWord` can contain special character, then you might want to escape it before passing it to RegExp constructor like in hwnd's answer – nhahtdh Nov 21 '14 at 02:46
  • Or [this answer](http://stackoverflow.com/a/4009787/1338292) and [this one](http://stackoverflow.com/a/7924240/1338292) in particular. – Ja͢ck Nov 21 '14 at 03:41

1 Answers1

2

Use a RegExp constructor to do this and you need to change .match(specialWord) to checkword instead.

checkword = new RegExp(specialWord, "g");
finalAnswer = userText.match(checkword);
hwnd
  • 69,796
  • 4
  • 95
  • 132