Insert a string at a specific index

前端 未结 18 879
眼角桃花
眼角桃花 2020-11-22 14:02

How can I insert a string at a specific index of another string?

 var txt1 = \"foo baz\"

Suppose I want to insert \"bar \" after the \"foo

18条回答
  •  情话喂你
    2020-11-22 14:22

    Take the solution. I have written this code in an easy format:

    const insertWord = (sentence,word,index) => {
        var sliceWord = word.slice(""),output = [],join; // Slicing the input word and declaring other variables
        var sliceSentence = sentence.slice(""); // Slicing the input sentence into each alphabets
        for (var i = 0; i < sliceSentence.length; i++) 
               {
            if (i === index) 
                   { // checking if index of array === input index
                for (var j = 0; j < word.length; j++) 
                           {   // if yes we'll insert the word
                    output.push(sliceWord[j]); // Condition is true we are inserting the word
                           }
                output.push(" "); // providing a single space at the end of the word
                     }
            output.push(sliceSentence[i]);  // pushing the remaining elements present in an array
                }
        join = output.join(""); // converting an array to string
        console.log(join)
        return join;
    }
    

提交回复
热议问题