+ 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 Respostas
+ 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