How to use slice() method In Javascript
The slice() method can be used to add a character to a string by removing the string after the index where you want to add the character and then again use the slice() method with the original string to get back the removed string.
Syntax:
initialStr.slice(startInd, endInd) + 'extraCharacter' + initialStr.slice(indexAfterWhichTheStringWasRemoved);
Example: The below code is a practical implementation of the slice() method to add charater to a string.
const str1 = "GeeksfoGeeks"
const updatedStr1 = str1.slice(0, 7) + 'r' + str1.slice(7);
const str2 = "JavaScrpt"
const updatedStr2 = str2.slice(0, 7) + 'i' + str2.slice(7);
console.log(updatedStr1, updatedStr2);
Output
w3wiki JavaScript
Add Characters to a String in JavaScript
In JavaScript, A string is a combination of multiple characters joined together to form a meaningful word. It can be a name or anything else. You can add an extra character to a string after it is defined to complete it or to practice adding characters.
There are several ways available in JavaScript to achieve this task as listed below:
Table of Content
- Using ‘+’ operator
- Using the concat() method
- Using template literals
- Using slice() method
- Using substring() method
- Using substr() method
- Using Array.prototype.join() Method