Previous answers here did not account for the whole word requirement. Indeed, it is difficult to achieve this since \b
word boundary does not support word boundaries with neighboring Hebrew Unicode symbols that we can only match with a character class using \u
notation.
I suggest using look-aheads and capturing groups to make sure we capture the whole Hebrew word ((^|[^\u0590-\u05FF])([\u0590-\u05FF]+)(?![\u0590-\u05FF])
that makes sure there is a non-Hebrew symbol or start of string before a Hebrew word - add a \s
if there are spaces between the Hebrew words!), and \b[a-z\s]+\b
to match sequence of whole English words separated with spaces.
If you plan to insert the <span>
tags into a sentence around whole words, here is a function that may help:
var str = 'so היי all whats up אתכם?';
//var str = 'so, היי, all whats up אתכם?';
var result = str.replace(/\s*(\b[a-z\s]+\b)\s*/ig, '<span>$1</span>');
result = result.replace(/(^|[^\u0590-\u05FF])([\u0590-\u05FF]+)(?![\u0590-\u05FF])/g, '$1<span>$2</span>');
document.getElementById("r").innerHTML = result;
span {
background:#FFCCCC;
border:1px solid #0000FF;
}
<div width="645" id="r"/>
Result:
<span>so</span><span>היי</span><span>all whats up</span><span>אתכם</span>?
If you do not need any punctuation or alphanumeric entities in your output, just concatenated whole English and Hebrew words, then use
var str = 'היי, User234, so 222היי all whats up אתכם?';
var re = /(^|[^\u0590-\u05FF])([\u0590-\u05FF]+)(?![\u0590-\u05FF])|(\b[a-z\s]+\b)/ig;
var res = [];
while ((m = re.exec(str)) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
if (m[1] !== undefined) {
res.push('<span>'+m[2].trim()+'</span>');
}
else
{
res.push('<span>'+m[3].trim()+'</span>');
}
}
document.getElementById("r").innerHTML = res.join("");
span {
background:#FFCCCC;
border:1px solid #0000FF;
}
<div width="645" id="r"/>
Result:
<span>היי</span><span>so</span><span>היי</span><span>all whats up</span><span>אתכם</span>