How can I split a long string in two in the nth space?

These lines can be long paragraphs, so I'm not sure if it is best to split the entire line with a space delimiter. I am trying to get, say, the first 10 words and wrap them in between:

'<span class="easing">' + string + '</span>'

Then join the second half of the original split. Suggestions for a super efficient way to do this? This will affect no more than three paragraphs per page at a time.

EDITED

Here the kicker - split should occur after the 9th word OR at the end of the first sentence (if this sentence is less than 9 words).

Example

 var origString = 'Coming into the world on Elvis' birthday with a doctor named Presley seemed fortuitous until, wielding the silvery smooth scalpel in his aged unsteady hand, the doctor sliced through the walls of my mother's uterus and into my unborn skin. Inside the warm soothing waters of my mother's womb, inside the silent weightlessness, I was safe. Then the prick of cold steel marked the first in a series of rude awakenings. I was scarred for life even before birth.'; var newString = '<span="easing">Coming into the world on Elvis' birthday with a doctor</span> named Presley seemed fortuitous until, wielding the silvery smooth scalpel in his aged unsteady hand, the doctor sliced through the walls of my mother's uterus and into my unborn skin. Inside the warm soothing waters of my mother's womb, inside the silent weightlessness, I was safe. Then the prick of cold steel marked the first in a series of rude awakenings. I was scarred for life even before birth.'; 

Or with a short sentence starting the paragraph:

 var origString = '"Is he okay? Tell me everything's okay" she pleas, her desperate need to confirm my health competing with her own need for consolation.'; var newString = '<span class="easing">"Is he okay?</span> Tell me everything's okay" she pleas, her desperate need to confirm my health competing with her own need for consolation.'; 
+4
source share
4 answers
 return string.replace(/.+?[,.?!]|.+$/, function(match, index, string){ var words = match.split(/\s+/); words[ words.length<10 ? words.length-1 : 9 ] += '</span>'; return '<span class="easing">' + words.join(" "); }); 

This matches the first thing like a sentence (or the entire line — excluding lines), and wraps the first 10 words of that range. Works for both your samples and small ones. Returns an empty string for an empty string, changes the regular expression to …|.*$ If you want an empty range.

+1
source

Given that you are going to scan no more than 100 characters (if you do not have a URI or very long words), then character scanning by character is very optimal. You can optimize this with .indexOf () in certain places, but you will lose everything you managed to check for every other character who could end the sentence.

 function spanomatic ( str, words ) { var i, l, c; for ( i=0, l=str.length; i<l; i++ ) { c = str.charAt(i); if ( c == ' ' ) { if ( words-- <= 0 ) { str = '<span>'+str.substring(0,i)+'</span>'+str.substring(i); break; } } else if ( ('?!.;:').indexOf(c) != -1 ) { str = '<span>'+str.substring(0,i)+'</span>'+str.substring(i); break; } } return str; } spanomatic ( 'Pass your string here', 9 ); 

(The above code assumes that your text will always correctly end correctly (i.e. contain at least one of?!. :) - if not, then it is possible that a paragraph with less than 9 words will endlessly. It may be fixed with a few changes, however ...)

note for future readers

If you go for a “super efficient” way of doing string searches, avoid regular expressions (unless you need their power). The accepted answer to this question is a concise and beautifully folded function - don't get me wrong - but it is about 70% slower than just scanning a line with a for loop (in my tests for FireFox and Chrome at least) ... and even with comparing after moving the regular expression definitions outside the Bergi function (i.e. using precompiled regular expressions, and not to recreate them every time the function is called).

http://jsperf.com/compare-regexp-vs-char-scanning

+2
source

How about this code:

 var str = 'asda adsfadsf asdfadfadsf adsfsdafadf. adfadfadfad adfadfdaf adfadfadf adfadf \afsgasfggasfg SFGDFGDSFGH dfghdsghdgas hadghdagh'; var sentences = [], words = str.split(' '); for (var i = 0; i < 9; i++) { if (words[i].lastIndexOf('.') !== -1) { sentences.push(words[i]); break; } else { sentences.push(words[i]); } } words.slice(sentences.length, words.length); $('<span>' + sentences.join(' ') + '</span>').appendTo($('#log')); 

I have a fiddle so you can test. You would like to do this in a loop with the remainder arr1.

Update:

If this is not just a complete stop, but also?!:; etc. then create RegExp and check instead of lastIndexOf('.')

0
source

Here. This is a bit of code golf. Unfortunately.

 $( 'p' ).html(function ( i, text ) { var re = /(.+?)\s/g, c = 0, res; while ( res = re.exec( text ) ) if ( ++c === 10 || res[1].slice( -1 ) === '.' ) break; var p = re.lastIndex; return '<span class="easing">' + text.slice( 0, p ) + '</span>' + text.slice( p ); }); 

Live demo: http://jsfiddle.net/3DaEV/

0
source

Source: https://habr.com/ru/post/1434394/


All Articles