Replace Part Of String At Specified Position
I want to replace a part of string at specified position(start, end) by another string in javascript Here is an example: 'Hello world this is a question' I want to replace the par
Solution 1:
For example with substring()
calls and concatenation (+
):
var msg="Hello world this is a question";
var replaced=msg.substring(0,6)+"friends"+msg.substring(11);
console.log(replaced);
Solution 2:
Method 1:
If you know the exact index you want to slice the string at, you should probably use javascript string.slice method like so:
var str = "Hello world!";
var part = str.slice(1, 5);
console.log(part); // "ello"
Method 2:
If you don't know the index, but you do know the string you want to replace, you can simply use string.replace method like so:
var input = "Hello world this is a question";
var result = input.replace("world", "friends");
console.log(result); // Hello friends this is a question
Solution 3:
You can use slice
to achieve this.
let str = "Hello world this is a question"functionreplace(st, en, val) {
str = str.slice(0, st + 1) + val + str.slice(en + 1)
}
replace(5, 10, 'friends')
console.log(str)
Solution 4:
You can try the replace()
and substring()
method
var str = "Hello world this is a question";
console.log(str.replace(str.substring(6, 11), "friends"));
Solution 5:
there is replace function in javascript
var replaceData = "Hello world this is a question";
console.log(replaceData.replace('world', 'friends'));
Post a Comment for "Replace Part Of String At Specified Position"