Greg Mercer
Greg Mercer

Reputation: 914

Javascript Whole word w

I'm looking for a way to display a paragraph of text and allow a user to click on a individual word to highlight it.

I found some code that will place a span around each word. And all of this works great, but...

When I have some text like say Soufflé it doesn't recognize it as one just one word.

Here is the code I'm using.

var p = $('#storyText');

p.html(function(index, oldHtml) {
    return oldHtml.replace(/\b([\w+-éñó\u00F1\u00E9]+)\b/g, '< span class="storyWord">$1< /span>');
})

It seems to work fine until I have an accent at the beginning or ending of a word.

Upvotes: 2

Views: 161

Answers (1)

Ricardo Tomasi
Ricardo Tomasi

Reputation: 35253

The problem is that word characters in a javascript RegExp are defined simply as [a-zA-z0-9_], so \b matches the "boundary" between them and an accented character. Matching the words directly is an improvement:

$.fn.highlightWords = function(){
  return this.html(function(i, html){
    return html.replace(/([\w'+-éñó\u00F1\u00E9])+/g, function(m){
        return '<span>'+m+'</span>'
    })
  })
}

$('p').highlightWords()

Demo: http://jsbin.com/elegod

Upvotes: 1

Related Questions