In JavaScript, strings are immutable, which means the best you can do is to create a new string with the changed content and assign the variable to point to it.
You'll need to define the replaceAt() function yourself:
String.prototype.replaceAt = function(index, replacement) {
return this.substring(0, index) + replacement + this.substring(index + replacement.length);
}
And use it like this:
var hello = "Hello World";
alert(hello.replaceAt(2, "!!")); // He!!o World
Answer from Cem Kalyoncu on Stack OverflowIn JavaScript, strings are immutable, which means the best you can do is to create a new string with the changed content and assign the variable to point to it.
You'll need to define the replaceAt() function yourself:
String.prototype.replaceAt = function(index, replacement) {
return this.substring(0, index) + replacement + this.substring(index + replacement.length);
}
And use it like this:
var hello = "Hello World";
alert(hello.replaceAt(2, "!!")); // He!!o World
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.substring(0,index) + chr + str.substring(index+1);
}
<button onclick="rep();">click</button>
javascript - Using .replace() at a specific index - Stack Overflow
javascript - How to find index on a string and replace? - Stack Overflow
Javascript using .replace() at a specific index of the search - Stack Overflow
javascript - Replace character at string index - Stack Overflow
function ReplaceAt(input, search, replace, start, end) {
return input.slice(0, start)
+ input.slice(start, end).replace(search, replace)
+ input.slice(end);
}
jsfiddle here
PS. modify the code to add empty checks, boundary checks etc.
From the "related questions" bar, this old answer seems to be applicable to your case. Replacing a single character (in my referenced question) is not very different from replacing a string.
How do I replace a character at a particular index in JavaScript?
The second substring index should be index + 1:
String.prototype.replaceAt = function(index, replacement) {
return this.substr(0, index) + replacement + this.substr(index + 1);
}
console.log("Hello World".replaceAt(5, "!!"))
console.log("Hello World".replaceAt(2, "!!"))
console.log("Hello World".replaceAt(2, "!!!"))
Run code snippetEdit code snippet Hide Results Copy to answer Expand
Is it possible to add the string as a parameter in an ES6 function?
const replaceAt = (index, replacement, string) => {
return string[:index] + replacement + string[index+1:]
}
You can do this with a little bit of manipulation, not requiring any regex.
I used this function to fetch the position (index) of another string within a string.
From there, it's as simple as returning a substring from the beginning to the found index, injecting your replacement, and then returning the rest of the string.
function replaceAt(s, subString, replacement, index) {
const p = s.split(subString, index+1).join(subString);
return p.length < s.length ? p + replacement + s.slice(p.length + subString.length) : s;
}
console.log(replaceAt("my text is my text and my big text", "my", "your", 2))
console.log(replaceAt("my text is my text and that's all", "my", "your", 2))
console.log(replaceAt("my text is my my my my text", "my", "your", 2))
Run code snippetEdit code snippet Hide Results Copy to answer Expand
There's not a built-in way to do that, but you can exploit the fact that .replace() can be passed a function:
let count = 0;
console.log("my text is my text and my big text".replace(/my/g, function() {
if (count++ === 2) return "your";
return "my";
}));
Run code snippetEdit code snippet Hide Results Copy to answer Expand
The function is passed the matched string and any groups as arguments, but in this case that's not really necessary. Strings are immutable in JavaScript. You have to create a new string instead:
str = str.substring(0, i) + ' ' + str.substring(i + 1);
If you're doing that a lot, you might convert the string to an array of characters, do the replacements, and then convert the array back into a string. Here's an ES2015+ example:
function replaceChar(str) {
return [...str].map(ch => ch === "-" ? " " : ch).join("");
}
console.log(replaceChar("testing-1-2-3"));
Your entire loop can be replaced by the replace method:
str = str.replace(/-/g, " ");
Strings are immutable in Javascript - you can't change individual characters. If you want to do something like that, you'll have to explicitly convert the string to an array first, perform your changes, and then join the array back into a string again:
function replaceChar (str) {
str = [...str];
let i
for (i = 0; i < str.length; i++) {
if (str[i] == '-') {
str[i] = ' '
}
}
return str.join('');
}
console.log(replaceChar('foo-bar-baz'));
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?
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 __.
Strings are immutable in Javascript - you can't modify them "in place".
You'll need to cut the original string up, and return a new string made out of all of the pieces:
// replace the 'n'th character of 's' with 't'
function replaceAt(s, n, t) {
return s.substring(0, n) + t + s.substring(n + 1);
}
NB: I didn't add this to String.prototype because on some browsers performance is very bad if you add functions to the prototype of built-in types.
Or you could do it this way, using array functions.
var a='I am a man'.split('');
a.splice.apply(a,[7,1].concat('wom'.split('')));
console.log(a.join(''));//<-- I am a woman
There is no such method in JavaScript. But you can always create your own:
String.prototype.replaceBetween = function(start, end, what) {
return this.substring(0, start) + what + this.substring(end);
};
console.log("The Hello World Code!".replaceBetween(4, 9, "Hi"));
The accepted answer is correct, but I wanted to avoid extending the String prototype:
function replaceBetween(origin, startIndex, endIndex, insertion) {
return origin.substring(0, startIndex) + insertion + origin.substring(endIndex);
}
Usage:
replaceBetween('Hi World', 3, 7, 'People');
// Hi People
If using a concise arrow function, then it's:
const replaceBetween = (origin, startIndex, endIndex, insertion) =>
origin.substring(0, startIndex) + insertion + origin.substring(endIndex);
If using template literals, then it's:
const replaceBetween = (origin, startIndex, endIndex, insertion) =>
`${origin.substring(0, startIndex)}${insertion}${origin.substring(endIndex)}`;