
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Inserting string at position x of another string using Javascript
Javascript does not give a direct way to achieve this. For this, we can use the slice method. The slice method extracts a section of a string and returns a new string.
To insert a string at a position x of another string, we can write the following function −
Example
function insertAtX(str1, str2, x) { return `${str1.slice(0, x)}${str2}${str1.slice(x)}` } console.log(insertAtX("Hello World", "Test", 5));
Output
This will give the output −
HelloTest World
This doesn't handle edge cases. You can add handling for those according to need.
- Related Questions & Answers
- Sorting string alphabetically and inserting underscores using JavaScript
- Insert a character at nth position in string in JavaScript
- Inserting empty string in place of repeating values in JavaScript
- Program to find the indexes where the substrings of a string match with another string fully or differ at one position in python
- Count appearances of a string in another - JavaScript
- Can part of a string be rearranged to form another string in JavaScript
- Number of times a string appears in another JavaScript
- Set characters at a specific position within the string in Arduino
- Remove characters from a string contained in another string with JavaScript?
- Finding the longest consecutive appearance of a character in another string using JavaScript
- String Transforms Into Another String in Python
- Reversing a string while maintaining the position of spaces in JavaScript
- Replace part of a string with another string in C++
- Inserting element at falsy index in an array - JavaScript
- Summing array of string numbers using JavaScript
Advertisements