I am trying to add a span tag around Hebrew and English sentence in a paragraph. E.g. \"so היי all whats up אתכם?\" will become :
[span]so[/span][span]היי
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 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, '$1');
result = result.replace(/(^|[^\u0590-\u05FF])([\u0590-\u05FF]+)(?![\u0590-\u05FF])/g, '$1$2');
document.getElementById("r").innerHTML = result;
span {
background:#FFCCCC;
border:1px solid #0000FF;
}
Result:
soהייall whats upאתכם?
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(''+m[2].trim()+'');
}
else
{
res.push(''+m[3].trim()+'');
}
}
document.getElementById("r").innerHTML = res.join("");
span {
background:#FFCCCC;
border:1px solid #0000FF;
}
Result:
הייsoהייall whats upאתכם