How do I replace a character at a particular index in JavaScript?
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
How to find index on a string and replace?
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, "!!!"))
How to replace characters by index in a JavaScript string?
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 __
.
Javascript using .replace() at a specific index of the search
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))
change words at particular location in javascript string
You need to make an array out of the string to replace by index.
The following should do the trick.
const changeChar = (str, newValue, index) => {
let splitted = str.split("");
splitted[index] = newValue;
return splitted.join("");
}
Replacing character at a particular index with a string in Javascript , Jquery
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.
replace a character according to its index until the word does not contain '_' in Python
Here's a sample with a slightly different twist. In this example if a character exists more than once in the word to guess, every location will be updated with that character.
def reveal_word():
string = '________'
word = 'Hercules'
while '_' in string:
letter = input('Enter your letter: ')
for index in range(0, len(string)):
if (string[index] == '_'):
if (word[index] == letter):
temp = list(string)
temp[index] = letter
string = "".join(temp)
print('String: ', string)
return string
print(reveal_word())
Here is some terminal output.
Enter your letter: e
String: _e____e_
Enter your letter: H
String: He____e_
Enter your letter: r
String: Her___e_
Enter your letter: c
String: Herc__e_
Enter your letter: u
String: Hercu_e_
Enter your letter: l
String: Hercule_
Enter your letter: s
String: Hercules
Hercules
Just another take on the puzzle.
Regards.
Related Topics
Chrome/Firefox Console.Log Always Appends a Line Saying 'Undefined'
How to Detect If Multiple Keys Are Pressed At Once Using JavaScript
How to Check For "Undefined" in JavaScript
Working With $Scope.$Emit and $Scope.$On
How to Stop the Browser Back Button Using JavaScript
JavaScript Window Resize Event
Sorting Object Property by Values
A Partial View Passing a Collection Using the Html.Begincollectionitem Helper
How to Disable Scrolling Temporarily
Difference Between Call and Apply
Async Function Returning Promise, Instead of Value
How to Create an Array Containing 1...N
Is It Right to Think of a JavaScript Function Expression That Uses the 'New' Keyword as 'Static'
How to Create an Object Property from a Variable Value in JavaScript