Skip to content Skip to sidebar Skip to footer

Regex Js: Replace Character By Unicode

I'm writing a jQuery Plug-In to replace spaces or non-spaces before ! or ? by a NARROW NO-BREAK SPACE as it's common in french. The thing is I don't manage to replace something by

Solution 1:

Looking at the text replacement only,

    text.replace(/[ \u202F]*([!\?])/g, "\u202F$1")

converts zero or more space or narrow non break space characters in text, followed by '!' or '?', into a single narrow non break space character followed by the '!' or '?' character matched (tested in Firefox and IE).

[ \u202F]

within the regular expression defines a character set to match spaces and includes the narrow non breaking space character itself. This could be extended to include specific additional space characters such as non breaking space (\u00A0), tabs, or replaced with \s to match any white space characters including line feeds.

Solution 2:

All spaces and non-spaces before ? will be replaced by your NARROW NO-BREAK SPACE

var text = $('p').text();
$('p').text(text.replace(/\s*\?/g, '\u202F\?')); 

https://jsfiddle.net/tct4e73c/1/

Update

Added !

var text = $('p').text();
$('p').text(text.replace(/.\s*(?=!|\?)/g, '\u202F')); 

https://jsfiddle.net/tct4e73c/2/

Post a Comment for "Regex Js: Replace Character By Unicode"