1

Hello i have a script where i have an textarea with the meta description and i have a input text field where i put the keyword. Then i print the matches and i have so far made this script:

var countDescription = tinymce.get('myTextEditor').getContent();
var count =  (countDescription.match(/is/g) || []).length;

And it works great, but my problem is instead of matching the word "is" i want it to match my string "u"

I have tried something like:

var count =  (countDescription.match("/" +u, "/g") || []).length;

But it really doesnt work..

Hope someone can help me out.

RappY
  • 302
  • 1
  • 11
  • I don't understand what's the reasoning behind your attempt. – elclanrs Mar 13 '15 at 08:39
  • I'm assuming `u` is a variable, hence the duplicate, but you did write the **string** `u`, and if it is just a string, it should be obvious that `countDescription.match(/u/g)` matches a literal `u` ? – adeneo Mar 13 '15 at 08:41
  • its a string with an word in. Example u could be service, gems, support, about us, and so on – RappY Mar 13 '15 at 08:45

1 Answers1

0

You need to use RecExp object here:

var count = (countDescription.match(new RegExp(u, 'g')) || []).length;

Where variable u contains the string you want to match.

PS: Make sure u doesn't have any special regex meta characters. Otherwise you will need to escape them.

anubhava
  • 664,788
  • 59
  • 469
  • 547
  • 1
    Thanks this works fantastic! So simple, i have been using days on this. Thanks alot! – RappY Mar 13 '15 at 08:43
  • Have any idea how i make this so it has to be a word for itself? something like var count = (countDescription.match(new RegExp('\b' + u + '\b', 'g')) || []).length; – RappY Mar 13 '15 at 08:51
  • Sorry to respond late, just came back online. It will be: `countDescription.match(new RegExp("\\b" + u + "\\b", 'g'))` – anubhava Mar 13 '15 at 09:56
  • 1
    Works great. Thanks alot. Marked as answered :-) – RappY Mar 13 '15 at 10:13