How to insert a character at a given position of a string?

Asked

Viewed 743 times

-1

How to insert a character at a given position of a string?

Ex: I have the string "abcdefg" and I want to add , before the "f" to stay "abcde,fg", how to do this?

  • 2

    What have you tried so far? Show us some code

1 answer

1


Here’s an example of how to do this:

var a = "abcdefg";
var b = ",";
var position = 5;
var output = [a.slice(0, position), b, a.slice(position)].join('');
console.log(output);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.