Skip to content Skip to sidebar Skip to footer

Do Word Boundaries Work On Symbol Characters?

I'm trying to implement word boundaries in my emoticons feature for a chat. But for some reason I can't seem to get the word boundaries to work. I am new to regex. So when I do: va

Solution 1:

Word boundaries \b represent a zero-width boundary between word characters \w (in javascript, [A-Za-z_]) and non-word characters \W (everything else).

Because of this, there will not be a boundary between two emoticons or when the emoticon is surrounded by spaces, punctuation, etc.

The simplest regex would be /[:;]-?[()]/gi, which supports smileys ) and frownies ( with optional dashes and eyes : or winks ;.

Edit:

This will require either a space or the beginning of the string (as a capturing group since Javascript doesn't support look-behinds), then it uses the above regex, then it must be followed by the end of string or whitespace.

var reg = /(\s|^)[:;]-?[()](?:\s|$)/gi;
var str = 'HiHi:) :) HiHiHi :)';
alert(str.replace(reg, '$1'));

Should replace in these situations: :-), cool :( not!

Should not replace in these situations: Digits:(0,1,2,3), hi :(.

Solution 2:

As \b will not work in this case, you could use:

var re = /(\s|^):\)(?!\S)/g;
var str = 'HiHi:) :) HiHiHi :)';
alert(str.replace(re, '$1'));

Which works like a space boundary.

You can add several smileys to it like so:

/(\s|^)(?::\)|:\(|:\||:\]|:\[)(?!\S)/g;

Post a Comment for "Do Word Boundaries Work On Symbol Characters?"