i'm having a string let say "Hello world"
And i need to replace the char at ex:3
by specifying index hw can we replace a char.
[JS]
var str = "hello world";
i need something like
str.replceAt(0,"h");
i'm having a string let say "Hello world"
And i need to replace the char at ex:3
by specifying index hw can we replace a char.
[JS]
var str = "hello world";
i need something like
str.replceAt(0,"h");
You can't. Take the characters before and after the position and concat into a new string:
var s = "Hello world";
var index = 3;
s = s.substr(0, index) + 'x' + s.substr(index + 1);
There is no replaceAt function in JavaScript. You can use the following code to replace any character in any string at specified position.
function Rep()
{
var str = 'Hello World';
str = setCharAt(str,4,'a');
alert(str);
}
function setCharAt(str,index,chr) {
if(index > str.length-1) return str;
return str.substr(0,index) + chr + str.substr(index+1);
}
<button onclick="Rep();">click</button>
Use this at somewhere before
String.prototype.replaceAt=function(index, char) {
return this.substr(0, index) + char + this.substr(index+char.length);
}
and use as following
var hello="Hello World";
alert(hello.replaceAt(3, "a"));
In Javascript strings are immutable so you ahve to do something like
var x = "Hello world"
var x = x.substring(0, i) + 'h' + x.substring(i+1);
To replace the character in x at i with 'h'