insert_tag

Wrapping a word in a html string
 avatar
user_9025834211
javascript
2 years ago
1.0 kB
4
Indexable
let insert_tag= ( target ,string , tag ) =>{

        const len = target.length;
        const slen = string.length;
        // Want to encapsulate this section that is in between
        const opening_index = target.indexOf(string);
        const closing_index = opening_index + slen;
        //Generate the closing and opening tags
        const opening = "<"+tag+">";
        const closing = "</"+tag+">";

        if (opening_index == -1 )
        {
            // Our word doesnt exist in this string
            console.log( "Error " + string + " Does not exist in "+target);
            return string;
        }
        // cut our string by pieaces
        let first_part = target.substring(0,opening_index);  //insert opening tag at the end of this string
        let second_part = target.substring(closing_index, len); //insert closing tag at a distence of tag
        first_part +=opening;
        second_part = closing +second_part;

        return first_part + string + second_part;

    }