jlafforgue
jlafforgue

Reputation: 287

Javascript - add a span for each letter

I'm trying to replace each letter of a div with many "span".

This code works except for letters with accents like "é". Can you help me please?

$('h2').each(function(){
  $(this).html($(this).text().replace(/(\w)/g, "<span>$&</span>"));
});

Upvotes: 4

Views: 4126

Answers (3)

z1m.in
z1m.in

Reputation: 1661

My variant without regexp

http://jsfiddle.net/d6pDG/

var html = $('.test').html();
var ret  = "";

$.each(html.split(''), function(k, v) {
   ret += "<span>" + v + "</span>";
});

$('.test').html(ret);

Upvotes: 3

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123377

\w doesn't include diacritic symbols so you need to specify an unicode range, like this

/[a-z\u00C0-\u00F6\u00F8-\017E]/gi

Upvotes: 5

hsz
hsz

Reputation: 152216

You can try with following regex:

/([^\x00-\x80]|\w)/g

Upvotes: 7

Related Questions