'replace character randomly in words of list
I wrote a function that puts "-" in given list randomly . just for privacy and for making it easier , i use a simple list here.but output is not my prefer answer.
example: if i enter "harddisk" ... output should be ha-dd-sk or -a-dd-sk or someyhing else
your help would be my appreciate.
const words = ['harddisk', 'laptop'];
let count, i = 0;
let wordsLength = words[i].length;
let splitted = words[i].split('');
let incompleteWords = '';
function convertToIncomplete(words) {
while (count < words[i].length / 2) {
let incompleteWords = Math.floor(Math.random() * wordsLength); //create new index
return incompleteWords;
}
}
let Words = prompt("enter your word : ");
//alert(convertToIncomplete(Words));
console.log(convertToIncomplete(Words));
this function just puts "-" randomly into a word that defined in given list
Solution 1:[1]
Try this code:
function convertToIncomplete(word){
const numberOfDashes = Math.floor(Math.random()*(word.length));
const places = [];
while(places.length < numberOfDashes){
const current = Math.floor(Math.random()*(word.length));
if(places.includes(current)) continue;
places.push(current);
}
let newWord = word;
for(let i=0;i<places.length;i++){
newWord = newWord.substring(0, places[i])+'-'+newWord.substring(places[i]+1);
}
return newWord;
}
let Words = prompt("enter your word : ");
//alert(convertToIncomplete(Words));
console.log(convertToIncomplete(Words));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Alireza Jahandoost |
