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/

3
  • Related: How to count string occurrence in string? Commented Nov 21, 2014 at 2: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 Commented Nov 21, 2014 at 2:46
  • Or this answer and this one in particular. Commented Nov 21, 2014 at 3:41

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.