SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Addict
    Join Date
    Jun 2007
    Posts
    358
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Word length of each word in a string

    hi,

    Suppose i have a string in variable, var textContent. It can have as low as 1 to even 200 words. What i want to know if there is a way to check the length each of the words in the string? so that lets say, if a word http:/www.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.com exists then i want to use alert to show message that the word is too long, for that i need to check length of all words in the string in "textConten".

    The problem is i have a textarea in my site, here if the users type such lengthy words, when it's later echoed through php it really messes up the layout so i decided to use textarea to echo it but it isn't breaking into next line with lengthy word (yes i have disabled scrolling).

    Thanks in advance

  2. #2
    SitePoint Addict
    Join Date
    Sep 2006
    Posts
    219
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi,

    It's not clear to me what you actually want to do with the lengths of the words, but debug the following self executing function and it should start you in the right direction:

    PHP Code:
    var test = function() {

        
    //the sentence to check
        
    var sentence "This is a long sentence of test with multiple word lengths";
        
        
    //split the sentence into individual words
        
    var words sentence.split(' ');
        
        
    //an array to hold our word lengths
        
    var lengths = [];
        
    //add length of each word to our lengths array
        
    for(var i=0,j=words.length;i<j;i++){
            
    lengths.push(words[i].length);
        }
        
    //sort the lengths (lowest lengths first)
        
    lengths.sort();
    }(); 
    Hope that helps,

    Dan

  3. #3
    SitePoint Guru
    Join Date
    Apr 2006
    Posts
    802
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You could just chop off any too long words in the string-

    var str='bob\'s wllwiammoionnwww is named jeiwuuvjrlovnmkli';

    str=str.replace(/\S{15,}/g,function(toolong){return toolong.substring(0,10)+'...'});

    /* returned value:
    bob's wllwiammoi... is named jeiwuuvjrl...
    */

    Or you could just break them up with spaces and hyphens.


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
  •