+ 2
JS how to insert “mytext” into a string at random places...
Let’s say text to be inserted is this “mytext” var tbi = “mytext” And then the string is this: var str = “this is the main text..bla bla” Now, insert tbi (“mytext”) into str at random places. Example: —> “this is the main text.. bla bla” to —> “thims is tyhe mteain text.. blax btla” So far I got it to insert the text every n characters, but I couldn’t do it I’m random. So, I thought I might ask for your help: https://code.sololearn.com/WGEs1980SV99/?ref=app
4 Réponses
+ 4
First, take a random number between 0 and text.length:
const i = Math.floor(Math.random() * text.length);
Next, slice your text into two parts, at position i:
const left = text.slice(0, i);
const right = text.slice(i + 1);
Then put it back together.
text = left + char + right;
Of course you want to do all this in a loop..
for(const char of mytext.split("")) {
...
}
+ 4
or use splice, its basicly same as Schindlabua's answer ( slice1 + chr + slice2 ). but the operation were done in array.
cost txtArr = txt.split();
const i = Math.floor(Math.random() * txt.length);
txtArr.splice(i, 0, chr);
txt = txtArr.join('')
another downside is you'll need polyfill for it to work in older browser
+ 4
1. Get the length of insert text, 'mytext', n
2. Get the length of str, m
3. Get n numbers of unique random numbers from 0 to m+1, randomArr
4. Sort randomArr in ascending order, sortedRandArr
5. Insert n characters into m string, according to sortedRandArr positions, output
6. You got the result output!
Build these 5 functions for getting the result.
Ginfio Show these functions to us once you've done.
+ 1
Calviղ did 1 - 3.
I’m don’t know how to do the #4. ascending order.
https://code.sololearn.com/WGEs1980SV99/?ref=app