0

I'm one of those people moving from JavaScript to TypeScript.

While converting my code, i stumpled across my function in JS to replace a number at a given index, not being able to fully convert.

String.prototype.replaceAt = function (index, replacement) {
  return this.slice(0, index) + replacement + this.slice(index + 1);
};
//Property 'replaceAt' does not exist on type 'String'. Did you mean 'replace'?ts(2551)

let string = "103456"
//"103456"

if (string.charAt(1) === "0") {
  let newString = string.replaceAt(1,2) //replaces at Index(1) 0 to become 2
  //Wanted outcome: "123456"
}

What this code does in JS

  1. Checks if the string has "0" as the second value (charAt(1))
  2. If true: replace the given number with 2 (...replaceAt(0,2))
  3. let newString become = "123456"

tl;dr check if match, if match = replace the value.

What I've Tried

As I'm still learning, I've checked up on declaring Globals, and interface StringConstructor. However, I'm unable to achieve the wanted outcome.

  • Side note: If you're going to modify built-in prototypes, use `defineProperty` to make your additions non-enumerable, **don't** assign to properties on `String.prototype` and such. – T.J. Crowder Sep 28 '22 at 08:44
  • I'm trying to find a TypeScript Alternative to replace a character at a given index, without modifying any built-in prototypes. the code provided was what i found working in JavaScript, but i do know modifying built-in prototypes isn't very optimal. – Jesper MENIX Lund Sep 28 '22 at 08:45
  • Just define a function, making sure to give its parameters proper types. Looks like you want to allow a couple of options for the replacement (not just string). Here's an example that allows `string`, `number`, or `boolean`: https://tsplay.dev/mZjO4m – T.J. Crowder Sep 28 '22 at 08:51
  • 1
    Thank you T.J - that was the exact thing i was looking for. I'm just pretty sure i tried out something almost identical as a function, where it still gave me issues. However it seems to be working as expected! Thank you so much, wish i could toss you the correct answer but.. well yeah topic closed. – Jesper MENIX Lund Sep 28 '22 at 08:58

0 Answers0