Skip to content

Instantly share code, notes, and snippets.

@efenacigiray
Last active August 23, 2023 17:55
Show Gist options
  • Save efenacigiray/9367920 to your computer and use it in GitHub Desktop.
Save efenacigiray/9367920 to your computer and use it in GitHub Desktop.
Javascript replace char at index
function replaceAt(string, index, replace) {
return string.substring(0, index) + replace + string.substring(index + 1);
}
@shoesCodeFor
Copy link

This is great! Thanks a bunch

@gatochuqui
Copy link

This is really cool. Thank you. I added this to detect hidden characters that cause problems in web page data

@gatochuqui
Copy link

Using your idea I did this to catch and replace hidden chars in text.

sampleData= '+ check if this has hidden chars';
// it does not if it did the + would be replaced by ERROR or something else
function ReplaceAt(string, index, replace) {

return string.substring(0, index) + replace + string.substring(index + 1);

}

function replaceX(STRG, OUT, IN) {
//20170329
try {
return STRG.split(OUT).join(IN);
}
catch (e) {
return "";
}
}

function detectFixHiddenChars(data) {

var chars = "";
var CK;
var KC;
for (k = 0; k < data.length; k++) {
    CK = data.charAt(k);
    KC = data.charCodeAt(k);
    if (KC < 32 || KC > 126) {
        data = ReplaceAt(data, k, '');
        data = replaceX(data, '+', 'Error ');//continue
    }
  return data
}

}

@srijan-paul
Copy link

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

@EthanVB123
Copy link

I still can't believe that this isn't automatically included in JS.

@awikio
Copy link

awikio commented Jul 5, 2020

Useful, thanks!

@loretoparisi
Copy link

loretoparisi commented Apr 6, 2021

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