Insert a String at a Specific Index

Insert a string at a specific index

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"

program to insert into a string at a selected index

Strings don't have an insert() method because they're immutable.

You can convert the string to a list, insert the new character into the list, then convert that back to a string with join().

string1 = input("input string: ")
index = int(input("select index: "))
add_char = input("add char: ")

string_list = list(string1)
string_list.insert(index, add_char)
string1 = "".join(string_list)
print(string1)

How to add a string in a certain position?

No. Python Strings are immutable.

>>> s='355879ACB6'
>>> s[4:4] = '-'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

It is, however, possible to create a new string that has the inserted character:

>>> s[:4] + '-' + s[4:]
'3558-79ACB6'

How to insert character in a string at a specific position?

You can use the substr() function!

If u want to insert 25 inside $str="Hello From Other Side "; at the position 2!

U can do

$pos=2;
$new_string= substr($str, 0, $pos). "25" . substr($str, $pos);

and the results would be:

"He25llo From Other Side "

Inserting string at position x of another string

var a = "I want apple";var b = " an";var position = 6;var output = [a.slice(0, position), b, a.slice(position)].join('');console.log(output);


Related Topics



Leave a reply



Submit