0

I have the following function in my JS

var p = $('.page p');
    p.html(function(index, oldHtml) {
        return oldHtml.replace(/\b(\w+?)\b/g, '<span class="word">$1</span>')
    });

This breaks up every word of paragraph. However words that have apostrophes (e.g don't, craig's) get split up to two part (e.g don and t)

How can I amend the code to make these complete words and keep in the apostrophe?

Thanks

  • FYI, you don't want to run such search/replace operations on the inner HTML of the element. It will affect any existing markup as well. Instead, you want to apply this to the inner *text* of the element. – Felix Kling Mar 06 '15 at 10:16
  • possible duplicate of [Regex to match words and those with an apostrophe](http://stackoverflow.com/questions/2596893/regex-to-match-words-and-those-with-an-apostrophe) – Joe Fitter Mar 06 '15 at 10:16

2 Answers2

1

Have you tried:

var p = $('.page p');

p.html(function(index, oldHtml) {
  console.log(oldHtml);
  return oldHtml.replace(/([\w']+)/g, '<span class="word">$1</span>');
  
});
.word {
  background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="page">
  <p>I'm so happy that I can't stop jumping up and down.</p>
  </div>
JLRishe
  • 99,490
  • 19
  • 131
  • 169
1

If you want to simply break a string into words, you could just split at the space and then join again...

$('.page p').each(function(){
  var p = $(this);
  var t = '<span class="word">' 
        + p.html().split(' ').join('</span> <span class="word">')
        + '</span>';
  p.html(t);
});

It depends what types of strings you're going to be dealing with of course, but this should be basic enough for a lot of circumstances.

Tom Dyer
  • 457
  • 2
  • 10