Shamoon
Shamoon

Reputation: 43589

How can I add a character to a random space of a string with JavaScript?

I have a string: The quick brown fox jumped over the lazy dogs. I want to insert a , (comma and space) into a random spot where there currently is just a (space). How can I accomplish this?

Upvotes: 0

Views: 39

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386746

Another way:

var string = 'The quick brown fox jumped over the lazy dogs.',
    array = string.split(' '),
    i = Math.random() * (array.length - 1) | 0;

array[i] += ',';
string = array.join(' ');
document.write(string);

Upvotes: 1

Related Questions