Is there a way to apply the replace
method on Unicode text in general (Arabic is of concern here)? In the example below, whereas replacing the entire word works nicely on the English text, it fails to detect and as a result, replace the Arabic word. I added the u
as a flag to enable unicode parsing but that didn't help. In the Arabic example below, the word النجوم should be replaced, but not والنجوم, but this doesn't happen.
<!DOCTYPE html>
<html>
<body>
<p>Click to replace...</p>
<button onclick="myFunction()">replace</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = "الشمس والقمر والنجوم، ثم النجوم والنهار";
var rep = 'النجوم';
var repWith = 'الليل';
//var str = "the sun and the stars, then the starsz and the day";
//var rep = 'stars';
//var repWith = 'night';
var result = str.replace(new RegExp("\\b"+rep+"\\b", "ug"), repWith);
document.getElementById("demo").innerHTML = result;
}
</script>
</body>
</html>
And, whatever solution you could offer, please keep it with the use of variables as you see in the code above (the variable rep
above), as these replace words being sought are passed in through function calls.
UPDATE: To try the above code, replace code in here with the code above.