SitePoint Sponsor

User Tag List

Results 1 to 3 of 3

Hybrid View

  1. #1
    FBI secret agent digitman's Avatar
    Join Date
    Sep 2004
    Location
    Work
    Posts
    697
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Split() question

    Hi,

    I'm building a small script which needs to show the number of time a word appears in a textarea. So if you type this in the textarea box:

    text text test text test
    Then it should say that 'test' appeared twice. This works fine by doing something like this:

    Code:
    word='test';
    arr=text.split(word);
    count=arr.length - 1;
    However, here's the problem. If I put in the following text:

    text text tests test text text
    Here, technicaly test appears twice, but it actually only appeared once (because the other time is was a part of 'tests' which is another word). I need to calculate this correctly, so it only shows the number of times test appeared as a whole word.

    I've considered doing something like this:
    Code:
    var arr=content.split(word + ' ');
    By doing this, it only matches if a space was typed right after 'test'. But if someone typed a question mark (?), exclamation mark (!), or any other punctuation character, it wouldn't match and that is also a problem.

    Can someone help me figure out a way to find the number of times a word appeared as a whole in the text? May be something could be done with regexps..

  2. #2
    FBI secret agent digitman's Avatar
    Join Date
    Sep 2004
    Location
    Work
    Posts
    697
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    P.S I found this code for getting the number of words in a string:

    Code:
    var wordsarray = words.split(/\b[\s,\.-:;]*/);
    return wordsarray.length;
    However, I need to show the number of times an individual word appeared in the text. If the reg exp there can be changed so it only matches if a word appeared in it, e.g:

    Code:
    var word='test';
    
    var wordsarray = words.split(word + /\b[\s,\.-:;]*/);
    Then that would work great. However I don't know much about regexps and don't know the correct way to do this..

    Any ideas?

  3. #3
    FBI secret agent digitman's Avatar
    Join Date
    Sep 2004
    Location
    Work
    Posts
    697
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    bump. anyone?


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •