William Hutter William Hutter - 2 months ago 6
jQuery Question

Add a line break at the half of text in jQuery

I would like to add a line break

<br/>
at the half of each block of text I have.
Meaning that if I have a tweet like this : "Google scientists find evidence of machine learning" it would be like this :

"Google scientists find evidence < br/> of machine learning"


How can I count the number of words in my string, divide this number by two and add a break in jQuery ?

Thanks

An example :

<span class="tweet-text">Nara Wants To Build A Better Recommendation Platform, Starts With Restaurants And A $4 Million Series...</span>


needs to become

<span class="tweet-text">Nara Wants To Build A Better Recommendation < br/> Platform, Starts With Restaurants And A $4 Million Series...</span>

Answer

Try this :

var words = "Google scientists find evidence of machine learning";
var arrofwords = words.split(" ");
var middle = arrofwords.length / 2;
arrofwords.splice(middle,0,"<br/>");
var output = arrofwords.join(" ");

Working demo

It splits the sentence using the spaces, inserts a <br/> after the middle word and joins it again ....

(Thanks @Felix Kling for suggestion in comment)

Althouth this has some issues - it doesnt put the <br/> where you wanted it ... and wouldn't be the most efficient for long sentences

Comments