JavaScript: how to select the first word(s) in a sentence

Recently I had to figure out a way to select the first 2 words in a sentence using JavaScript. I wanted to wrap them in a class so that I could give them some additional CSS styling. I figured it’d be mad easy, but it took a little bit of head scratching until I figured out at least one way to do it.

I’ve got an HTML element with an ID of ‘niceText’ that I’m looking to grab. I’ll save the string as a variable called ‘niceText’.

var niceText = $('#niceText').text();

I’ll also save the opening and closing spans I’m going to wrap the text in as variables like so:

var openSpan = '<span class="grey">', closeSpan = '</span>';

Next, we’ll use the native JavaScript split method. This makes an array out of a string – all you have to do is to specify the separator that’ll be used to divide the string. In this case the separator is a blank space, so we can write:

niceText = niceText.split(' ');

Our variable ‘niceText’ is now an array of strings (go ahead and use your console to take a peek at what’s happened to our variable).

Next we’ll add the span to the start of the array using the unshift method. It you’ve ever used the push method, this is very similar except that it adds elements to the beginning of the array instead of to the end.

niceText.unshift( openSpan );

Fab. We now need to add the closing span to the array. We can do this with the splice method. If you’re not sure how this method works, do have a good read of the docs as it can come in super handy when performing array surgery!

As I want to wrap the first 2 words in my sentence, I’m going to add the closing span as the 4th item in the array. The first item is now my opening span, then comes the two opening words, then my closing span. The second value in splice indicates how many values, if any, to remove from the array. We’re not removing any, just adding, so this will be equal to 0.

niceText.splice( 3, 0, closeSpan );

Next I’ll turn the array back into a string using join. Like split, join accepts a value for the separator, only this time, the separator is what will be printed between every array item. As this is just a sentence, we want to add a space between the words, so we can write:

niceText = niceText.join(' ');

Finally I’ll add the string to my HTML element like so:

$('#niceText').html( niceText );

That’s it! Here’s the whole function.

jQuery( function($){

   /* Get the text of the element I'm after */
   var niceText = $('#niceText').text(),
      openSpan = '<span class="grey">', closeSpan = '</span>';

   /* Make the sentence into an array */
   niceText = niceText.split(' ');

   /* Add span to the beginning of the array */
   niceText.unshift( openSpan );

   /* Add  as the 4th value in the array */
   niceText.splice( 3, 0, closeSpan );					

   /* Turn it back into a string */
   niceText = niceText.join(' ');					

   /* Append the new HTML to the header */
   $('#niceText').html( niceText );

});

If you’re not already using jQuery in your site, it might be a bit much to add it for just this tiny function! Rather, you can simply replace

var niceText = $('#niceText').text();

with

var niceText = document.getElementById('niceText').textContent;

and

$('#niceText').html( niceText );

with

document.getElementById('niceText').innerHTML = niceText;

Grand stuff. Hope it comes in useful!

2 thoughts on “JavaScript: how to select the first word(s) in a sentence”

  1. How would you do this for each item in a list? I\’m running into issues trying to grab the text while doing an each loop. Any ideas?

  2. Hi Dan, this should work.

        $.each( $('ul.my-list li'), function () {
          var niceText = $(this), openSpan = '', closeSpan = '';
          /* Make the sentence into an array */
          niceText = niceText.text().split(' ');
    
          /* Add span to the beginning of the array */
          niceText.unshift( openSpan );
    
          /* Add  as the 4th value in the array */
          niceText.splice( 3, 0, closeSpan );
    
          /* Turn it back into a string */
          niceText = niceText.join(' ');
          $(this).html(niceText);
        });

Comments are closed.