Last active
August 23, 2023 17:55
-
-
Save efenacigiray/9367920 to your computer and use it in GitHub Desktop.
Javascript replace char at index
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function replaceAt(string, index, replace) { | |
return string.substring(0, index) + replace + string.substring(index + 1); | |
} |
I still can't believe that this isn't automatically included in JS.
Useful, thanks!
I would be worth to have a replaceAll
that makes use of replaceAt
but with index update like (without RegExp
of course)
text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\nLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\nLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
replaceAll([{
text: "Lorem",
rep: "A",
index: idx1
},
{
text: "ipsum",
rep: "B",
index: idx2
},
{
text: "eiusmod"
rep: "C",
index: idx3
}
])
A B dolor sit amet, consectetur adipiscing elit, sed do C tempor incididunt ut labore et dolore magna aliqua.\nA B dolor sit amet, consectetur adipiscing elit, sed do C tempor incididunt ut labore et dolore magna aliqua.\nA B dolor sit amet, consectetur adipiscing elit, sed do C tempor incididunt ut labore et dolore magna aliqua
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks. I don't understand why using var[index] = value doesn't give the desired result when trying to alter characters in a string but doesn't throw an error either. That's strange