我试图让一个函数用破折号覆盖多单词区域,但不用 JavaScript 中的破折号覆盖单词之间的空格。所以,我基本上需要 JS 来忽略空格(或者维护然后?),但我在网上找到的只是如何从字符串中删除空格。如果我这样做,那么覆盖该区域的破折号之间仍然不会有空格(尽管从技术上讲,没有空格的长度是正确的)。
这是我正在使用的函数:
开始日常工作:
sentenceList = Sentence.split(",");
wordNumber = (- 2);
每帧:
var _pj;
function replaceWithdash(sentenceList, currentWordNumber) {
var index, result, word;
result = "";
index = 0;
while ((index < sentenceList.length)) {
word = sentenceList[index];
if ((index !== currentWordNumber)) {
result = ((result + ("-".repeat(word.length))) + " ");
} else {
result = ((result + word) + " ");
}
index = (index + 1);
}
return result;
}
区域由分隔符“,”分隔,以便可以包含多个单词。变量“word”基本上通过句子中的这些区域进行索引。函数“replaceWithdash”用破折号替换“word”长度(总区域)。我不知道如何以某种方式保持按区域显示,但让 ReplaceWithdash 函数忽略或保留空格。输入:狗,吃了,食物。
当前显示:
------- --- --------
The dog --- --------
所需的显示:
--- --- --- --- ----
The dog --- --------
有谁知道解决这个问题的方法吗?
如果我理解正确的话,这就是你正在寻找的,对吗?
function replaceWithdash(sentenceList, currentWordNumber) {
const regions = sentenceList.split(",")
const sigil = regions.map(s => s.replaceAll(/[^\s]/g, "-"))
if (currentWordNumber !== undefined) {
sigil.splice(currentWordNumber, 1, regions[currentWordNumber])
}
return sigil.join("")
}
str = "The dog, ate, the food"
console.log(replaceWithdash(str))
//"--- --- --- --- ----"
console.log(replaceWithdash(str, 0))
//"The dog --- --- ----"
console.log(replaceWithdash(str, 1))
//"--- --- ate --- ----"
console.log(replaceWithdash(str, 2))
// "--- --- --- the food"
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)