m1crdy
m1crdy

Reputation: 1401

Insert string to random place inside another string

i got this code:

var set = ["?","(",")","$","%","!"];
var randomZahlZeichen = (Math.floor(Math.random() * 6)+1).toString();
var randomZeichen = set[randomZahlZeichen];
var content = editor.session.getTextRange(editor.getSelectionRange());
content = content.substring(2);
var result15 = "</"+randomZeichen+content;

It inserts a random token into the string content at the third spot. But know I want to insert that random token into a random spot at that string. How? Is there a random function for that substring without cutting? Ty

Upvotes: 2

Views: 1706

Answers (1)

Guffa
Guffa

Reputation: 700582

Put the string together without the character, pick a random position, and split the string there with the character between:

var result15 = "</"+content;
var pos = Math.floor(Math.random() * (result15.length + 1));
result15 = result15.substr(0, pos) + randomZeichen + result15.substr(pos);

Note: The random position is anywhere in the string, including first and last. You would adjust the random number if there is some position that you want to avoid.

Upvotes: 2

Related Questions