JSFiddle - React, Tailwind, and code Playground

by pierian_design

JavaScript

var str = 'text!';
var find = ['t', 't!'];
var toAdd = {
    't': '+', 't!': '???'
};

function getEntries(haystack, needle) {
    
    let pos = 0; // Position Ref
    let result = []; // Final output of all index's.
    let hayStackLower = haystack.toLowerCase();
    let needleLower = needle.toLowerCase();
    
    // Loop to check all occurrences 
    while (hayStackLower.indexOf(needleLower, pos) != -1) {
      result.push(hayStackLower.indexOf(needleLower , pos));
      pos = hayStackLower.indexOf(needleLower , pos) + 1;
    }

    return result;
}

function getCoords(str, whatFind) {

    return whatFind.reduce((aAcc, sFind) => {

        var re = getEntries(str, sFind);

        re.forEach((entry, i) => {

            var isAlreadyIn = aAcc.find(e => e.pos === entry);
            
            !isAlreadyIn && aAcc.push({ key: sFind, pos: re[i] });
        });
        return aAcc;
        
    }, []).sort((a, b) => b.pos - a.pos);
}

var coords = getCoords(str, find);


var extraLength = str.length;
var newStr = coords.reduce((_str, coord) => {

    str = str.slice(0, coord.pos) + coord.key + toAdd[coord.key] + _str.slice(coord.pos + coord.key.length);
    
    return str;
}, str);

console.log(coords, newStr, str);