我想写这个google spreadsheet javascript代码来替换字符串中的随机字母。
我已经创建了一个代码,但不是随机的,而且它还用下划线替换空格(这是有问题的)。
我感兴趣的最终结果是从这个开始(句子是法语顺便说一下):
'J’habite à New York.'
要这样做:
'_’h_b_t_ à _ew _or_.'
假设给定一个句子,至少有一半的字母必须用下划线替换。
谢谢你的帮助。(ps:我不是程序员)
到目前为止,我的代码如下:
var v = [['J’habite à New York.', 'Sì', ], ['Je m’appelle John. !']];
for (var r in v){
for (var c in v[r]){
var d = v[r][c];
var l = d.length;
var u = l;
while(u > 0){
var res = d.replace(d[u-2], '_');
d = res;
u = u - 2;
}
console.log(res);
}
}发布于 2018-07-06 23:04:45
您可以尝试如下所示:)
var a = "Text i want to replace text from";
var splitted = a.split('');
var count = 0; // variable where i keep trace of how many _ i have inserted
while(count < a.length/2) {
var index = Math.floor(Math.random()*a.length); //generate new index
if(splitted[index] !== '_' && splitted[index] !== ' ') {
splitted[index] = '_';
count++;
}
}
var newstring = splitted.join(""); //the new string with spaces replaced编辑:我现在在控制台上试过了,看起来很好用。它给你带来了什么问题?
2°编辑:你可以这样做:
splitted[index] = ' _ ';而不是
splitted[index] = '_';另请注意,我将if条件从:
if(splitted[index] !== '_')至
if(splitted[index] !== '_' && splitted[index] !== ' ')避免将空格替换为“_”
:)
发布于 2018-07-06 22:55:48
你有点太复杂了。只需将字符串转换为字符数组,然后将其映射到替换了某些字母的字符数组,并将其转换回字符串。
function replace(str) {
return str.split("").map(char => Math.random() > 0.5 ? "_" : char).join("");
}
var v = [
['J’habite à New York.', 'Sì', ],
['Je m’appelle John. !', 'Non!',]
];
for (const pair of v) {
pair[0] = replace(pair[0]);
pair[1] = replace(pair[1]);
}
console.log(v)
https://stackoverflow.com/questions/51212980
复制相似问题