Fred J. Fred J. - 4 months ago 7
Javascript Question

replace part of end of string with equal number of given characters

Given the string

abc11111
and
232
.

Is there an elegant way to replace the last 3 "in this case" characters so that the results would be
abc11232
? Thanks

Answer

Use JavaScript String#slice method

var str1 = 'abc11111',
  str2 = '232';

console.log(
  str1.slice(0, -str2.length) + str2
);


Or use String#substr or String#substring method.

var str1 = 'abc11111',
  str2 = '232';

console.log(
  str1.substring(0, str1.length - str2.length) + str2
);

// or

console.log(
  str1.substr(0, str1.length - str2.length) + str2
);

Comments