Javascript: replace “x” only if it is the first word of the text and not elsewhere

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".

+4
4

, .replace . RegExp , .

.replace 1+n th . .

RegExp, , , .

JS

var myFunction = function() {
    var str = document.getElementById("text1").value;
    var regexs = ['(k)','(^e|\\se)', '(e)'];
    var replacers = ['g', 'B', 'ar'];
    var re = new RegExp(regexs.join("|"),"gi");
    // you would need to add variables to the function for each matching group you add (currently there are 3 so we have 3 groups)
    str = str.toLowerCase().replace(re, function(raw, group0, group1, group2){
        if(typeof group0 !== "undefined"){
            return replacers[0]; // replaces with 'g'
        }else if(typeof group1 !== "undefined"){
            // skip over the first character (white space) and concatenate the replacement
            return raw[0] + replacers[1]; // replaces with 'B'
        }else if(typeof group2 !== "undefined"){
            return replacers[2]; // replaces with 'ar'
        }
        return raw;
    });
    document.getElementById("demo").innerHTML = str;
};
document.getElementById('go').addEventListener('click', myFunction);

CSS

#demo{
    white-space:pre;
}

: .innerHTML CSS .

JS FIDDLE

+3

.

function myFunction() {
   var str = document.getElementById("text1").value; 
    str = str.toLowerCase().split('k').join('g').split(' e').join(' B').split('\\n').join(' B').split('e').join('ar');
    document.getElementById("demo").innerHTML = str;
}

, .

+1

The simplest workaround.

<script type="text/javascript">
var myfunction = function(){

  var f = document.getElementById('text1').innerHTML;
  var c = f.replace(/e/ig,'ar').replace(/\bar/ig,'B').replace(/k/ig,'g');
  document.getElementById('text1').innerHTML = c;

}
</script>
+1
source

It works.

<textarea id="source" cols="5" rows="5">
e mi e
ke fo
e di
</textarea>

<button  type="button" onclick="convert()">Convert</button>

<textarea id="destination" cols="5" rows="5">
</textarea>

<script>
function replaceWord(searchFor, replaceWith, paragraph) {
    if (paragraph) {
        var lines = paragraph.split('\n');
        for (lineNo = 0; lineNo < lines.length; lineNo++) {
            var words = lines[lineNo].split(' ');
            for (wordNo = 0; wordNo < words.length; wordNo++) {
                if (words[wordNo] === searchFor) {
                    words[wordNo] = replaceWith;
                }
            }
            lines[lineNo] = words.join(' ');
        }

        paragraph = lines.join('\n');
    }

    return paragraph;
}

function replaceWords(wordMap, paragraph) {
    for(var searchFor in wordMap)
    {
        if(wordMap.hasOwnProperty(searchFor))
        {
            paragraph = replaceWord(searchFor, wordMap[searchFor], paragraph);
        }
    }
    return paragraph;
}

function convert() {

    var mapObj = {
        "ke":"gar",
        "e": "B"
    };

    var source = document.getElementById("source");
    var destination = document.getElementById("destination");

    destination.value = replaceWords(mapObj, source.value);
}
</script>

Here is jsFiddle. https://jsfiddle.net/1egs7zgc/

For what it's worth, your mapObj is actually not an array, but an object.

+1
source

Source: https://habr.com/ru/post/1667309/


All Articles