Insert string at specific index of another string in JS
A straightforward approach is to separate our string into multiple substrings and insert the required string at the specific index.
First, we will introduce the syntax and parameters of the methods we are using:
The Slice() method returns a subarray that copies the value from the start parameter to the end parameter, where the start and end represent the index of the element in that array. The original array is immutable.
slice() slice(start) slice(start, end)
- start (Optional): Index zero-based, from which to begin the extraction.
- An offset from the sequence’s end can be indicated by using a negative index. The final two parts of the sequence are taken out by slice(-2).
- If ‘start’ is undefined, ‘slice’ starts from the index 0.
- An empty array is returned if ‘start’ exceeds the sequence’s index range.
- end (Optional): The first entry to remove from the returning array by index. slice only includes the text up to the end. Slice(1,4), for instance, extracts the second element via the fourth element (elements indexed 1, 2, and 3).
- A negative index can be used to indicate an offset from the end of the sequence. Slice(2, -1) extracts the 3rd element from the end of the sequence to his 2nd element.
- If ‘end’ is omitted, slices are extracted to the end of the sequence (arr.length).
- If ‘end’ is greater than the length of the sequence, slices are extracted to the end of the sequence (arr.length).
We will use the method above to insert a new string into another string:
let txt = "Welcome learnshareIT" let txt2 = txt.slice(0, 8) + "to " + txt.slice(8) console.log(txt2)
Welcome to learnshareIT
Using the same demonstrated code snippet, substring() will work similarly.
Combination substring() and toString() method
The substring() method returns the portion of the string between the start index and end index or to the end of the string.
- indexStart: is the cutting start position.
- indexEnd: is the cutting end position.
The toString() method returns a string representing the object.
- type: is an optional parameter, returns type radix.
We will use the toString() and subString() method if you want to add a number value to a specific index.
let txt = "Welcome learnshareIT" // Slicing, converting and concatenating string let txt2 = txt.substring(0, 8) + 100..toString() + " members of" + txt.substring(7) console.log(txt2)
Welcome 100 members of learnshareIT
To understand the morphism of the string data type, you may check out this document.
Maybe you are interested:
Name of the university: UTC