If I have the string "hello" and I want to replace the second and third character with _, how can i do that, given only the location of the substring, not what it actually is.
Asked
Active
Viewed 1.9k times
0
-
I tried the replace() method, but you need a substring for that, not just the location @Sednus – vcapra1 Mar 15 '13 at 20:52
-
Please see: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/substring – Amy Mar 15 '13 at 20:53
2 Answers
9
String.prototype.replaceAt=function(index, character) {
return this.substr(0, index) + character + this.substr(index+character.length);
}
str.replaceAt(1,"_");
str.replaceAt(2,"_");
Taken from: How do I replace a character at a particular index in JavaScript?
8
str = str.replace( /^(.)../, '$1__' );
The .
matches any character except a newline.
The ^
represents the start of the string.
The ()
captures the character matched by the first .
so it can be referenced in the replacement string by $1
.
Anything that matches the regular expression is replaced by the replacement string '$1__'
, so the first three characters at the start of the string are matched and replaced with whatever was matched by the first .
plus __
.

MikeM
- 13,156
- 2
- 34
- 47
-
[This page](https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Regular_Expressions) is really helpful to learn more about JavaScript regular expressions. – jahroy Mar 15 '13 at 20:55
-
He can, but it is better to look into replace() and Regular Expressions: http://www.w3schools.com/jsref/jsref_replace.asp / and this / http://www.regular-expressions.info/reference.html – turiyag Mar 15 '13 at 20:56