tags:

views:

2048

answers:

4

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");
A: 

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);
Guffa
Actually, yes, you can, but it would be an overkill. You could set up a regular expression to skip the first index - 1 characters and match the character at the index. You can use String.replace with that regular expression to do a direct, in-place replacement. But it's an overkill. So, in practice you can't. But in theory, you can.
Ates Goral
@Ates: The replace function doesn't do an in-place replacement, it creates a new string and returns it.
Guffa
+2  A: 

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>
rahul
+7  A: 

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"));
Cem Kalyoncu
Note that it's generally not a good idea to extend base JavaScript classes. Use a plain utility function instead.
Ates Goral
I must ask why? Prototype support is there for this purpose.
Cem Kalyoncu
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'

DevDevDev