2

I'm sure this was supposed to work, but I can't get it doing what I want it to:

new_str = old_str.replace(3, "a");
// replace index 3 (4th character) with the letter "a"

So if I had abcdef then above should return abcaef but I must have gotten something wrong. It is changing characters, but not the expected ones.

Either native JS or jQuery solution is fine, whatever is best (I'm using jQuery on that page).

I've tried searching but all tutorials talk of Regex, etc. and not the index replace thing.

FelipeAls
  • 21,711
  • 8
  • 54
  • 74

2 Answers2

2

You appear to want array-style replacement, so convert the string into an array:

// Split string into an array
var str = "abcdef".split("");

// Replace char at index
str[3] = "a";

// Output new string
console.log( str.join("") );
Sampson
  • 265,109
  • 74
  • 539
  • 565
1

Here are three other methods-

var old_str= "abcdef",

//1.
new_str1= old_str.substring(0, 3)+'a'+old_str.substring(4),

//2.
new_str2= old_str.replace(/^(.{3}).(.*)$/, '$1a$2'),

//3.
new_str3= old_str.split('');
new_str3.splice(3, 1, 'a');

//return values

new_str1+'\n'+new_str2+'\n'+ new_str3.join('');

abcaef
abcaef
abcaef
kennebec
  • 102,654
  • 32
  • 106
  • 127