4

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>"));
});
dda
  • 6,030
  • 2
  • 25
  • 34
jlafforgue
  • 287
  • 2
  • 5
  • 15
  • Just the letters? no numbers, spaces, !@#$^&..., etc? – Lidor Jul 04 '13 at 08:02
  • Native JS regex has problems with Unicode characters. Do you need to wrap only letters, or any characters? – VisioN Jul 04 '13 at 08:04
  • It works with space but it's a good idea to take numbers and special chars if it's possible. I don't know modify this regex... The more important are characters ! – jlafforgue Jul 04 '13 at 08:05
  • http://stackoverflow.com/questions/5436824/matching-accented-characters-with-javascript-regexes – steo Jul 04 '13 at 08:05
  • 1
    you can simplify the loop by using `$('h2').text(function(){ return $(this).text().replace(/(\w)/g, "$&") })` – Arun P Johny Jul 04 '13 at 08:21

3 Answers3

7

You can try with following regex:

/([^\x00-\x80]|\w)/g
hsz
  • 148,279
  • 62
  • 259
  • 315
5

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

/[a-z\u00C0-\u00F6\u00F8-\017E]/gi
Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177
3

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);
Maxime Lorant
  • 34,607
  • 19
  • 87
  • 97
z1m.in
  • 1,661
  • 13
  • 19