Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert a string at a specific index

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" how can I achieve that?

I thought of substring(), but there must be a simpler more straight forward way.

like image 959
Jiew Meng Avatar asked Nov 30 '10 12:11

Jiew Meng


People also ask

Which method inserts a string at a specified index position?

The splice() method is used to insert or replace contents of an array at a specific index. This can be used to insert the new string at the position of the array.

How do you add a string to a specific position in Python?

If you need to insert a given char at multiple locations, always consider creating a list of substrings and then use . join() instead of + for string concatenation. This is because, since Python str are mutable, + string concatenation always adds an aditional overhead.


2 Answers

Inserting at a specific index (rather than, say, at the first space character) has to use string slicing/substring:

var txt2 = txt1.slice(0, 3) + "bar" + txt1.slice(3); 
like image 194
Tim Down Avatar answered Oct 26 '22 23:10

Tim Down


You could prototype your own splice() into String.

Polyfill

if (!String.prototype.splice) {     /**      * {JSDoc}      *      * The splice() method changes the content of a string by removing a range of      * characters and/or adding new characters.      *      * @this {String}      * @param {number} start Index at which to start changing the string.      * @param {number} delCount An integer indicating the number of old chars to remove.      * @param {string} newSubStr The String that is spliced in.      * @return {string} A new string with the spliced substring.      */     String.prototype.splice = function(start, delCount, newSubStr) {         return this.slice(0, start) + newSubStr + this.slice(start + Math.abs(delCount));     }; } 

Example

String.prototype.splice = function(idx, rem, str) {      return this.slice(0, idx) + str + this.slice(idx + Math.abs(rem));  };    var result = "foo baz".splice(4, 0, "bar ");    document.body.innerHTML = result; // "foo bar baz"

EDIT: Modified it to ensure that rem is an absolute value.

like image 29
user113716 Avatar answered Oct 26 '22 22:10

user113716