How to use String.substring() Method In Javascript
The substring() method extracts the characters from a string between two specified indices and returns a new string. We can utilize this method to split the original string into two parts at the specified index, then concatenate the substring in between.
Syntax:
string.substring(startIndex, endIndex)
- startIndex: The index at which to begin extraction. If negative, it is treated as str.length + startIndex. (For example, if startIndex is -3, it is treated as str.length – 3.)
- endIndex: The index at which to end extraction. If omitted, the slice goes to the end of the string. If negative, it is treated as str.length + endIndex. (For example, if endIndex is -3, it is treated as str.length – 3).
Example:
// Input string
let str = 'GeeksGeeks';
// Input Substring
let subStr = 'for';
// Index to add substring
let pos = 5;
// Using substring() to insert the substring
let result = str.substring(0, pos) + subStr + str.substring(pos);
console.log(result);
Output
w3wiki
JavaScript Insert a string at position X of another string
Given two strings, the task is to insert one string in another at a specified position using JavaScript. We’re going to discuss a few methods, these are: