I am working on simple JS code to replace some words with others in the text using an array.
<textarea id="text1">
e mi e
ke fo
e di
</textarea>
<button type="button" onclick="myFunction()">try</button>
<pre id="demo"></pre>
<script>
function myFunction() {
var str = document.getElementById("text1").value;
var mapObj = {
"k":"g",
" e": "B",
"e":"ar"
};
var re = new RegExp(Object.keys(mapObj).join("|"),"gi");
str = str.toLowerCase().replace(re, function(matched){
return mapObj[matched];
});
document.getElementById("demo").innerHTML = str;
}
</script>
Result:
ar mi B
gar fo
ar di
But I want to have this:
B mi B
gar fo
B di
If "e"you need to change to " e"(separated eby a space in front of it), then " e"there will be " e", but "ar", so in the array I put " e"above "e"and it works well.
However, the problem is that the text may contain highlighted "e"as the first word of the entire text or as the first word of the line without a space in front of it. When this happens, I can replace this highlighted "e"with "B"and not replace it with "ar".