skip to Main Content

I am a newbie, and have a pile of data strings (sentences). I’m trying to divide each sentence into substrings where each string’s length does not exceed the length of longest single word in that sentence, and returning all words in their original sequence with line breaks (Photoshop carriage return, “r”) dividing the substrings, for that sentence. The words in each string are not hyphenated (only full words or groups of words broken at where a space would be*).* Edit: using the maximum characters, up to the longest word’s character count… so a line would have 2 or 3 words possibly, up to the length of the longest word.

I’ve found examples that split and count the array of words, order them by character length, or add line breaks at set characters, all spaces, etc. But none where I know enough to see an easy modification for this outcome. Any help is greatly appreciated.

2

Answers


  1. Using replace you can replace all the spaces with n to get the result.

    a = 'This show navigation menu when you scroll up page 0px up (in right-way). But trying to show after 200px (on page scroll-up) means not showing right way want show and hide after 200px when scroll n up page.'
    b = a.replace(/s{1,}/g,"n");
    alert(b)
    Login or Signup to reply.
  2. Try using .split with a regex:

    var a = 'This show navigation menu when you scroll up page 0px up (in right-way). But trying to show after 200px (on page scroll-up) means not showing right way want show and hide after 200px when scroll n up page.'
    var outputArray = a.split(/s+/);
    console.log(outputArray);
    

    If you want a more direct way:

    var a = 'This show navigation menu when you scroll up page 0px up (in right-way). But trying to show after 200px (on page scroll-up) means not showing right way want show and hide after 200px when scroll n up page.'
    
    a.match(RegExp('.{0,' + Math.max.apply(0, a.match(/w+/g).map(function(l) {
        return l.length;
    })) + '}', 'g');
    

    ES6:

    a.match(RegExp(`.{0,${Math.max(...a.match(/w+/g).map(l=>l.length))}}`), 'g')
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search