如何使 Java 脚本忽略或保留空格,而不是删除它们

How to make Java Script ignore or maintain spaces, not delete them

我试图让函数用破折号覆盖多词区域,但不在 Java 脚本中用破折号覆盖单词之间的 space。所以,我基本上需要 JS 来忽略 spaces(或者保持不变?),但我在网上找到的只是如何从字符串中删除 spaces。如果我这样做,那么覆盖该区域的破折号之间仍然没有 spaces(尽管从技术上讲它是没有 space 的正确长度)。 这是我为此工作的功能: 开始例程:

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;
}

区域由分隔符“,”分隔,以便包含多个单词。变量“词”基本上通过句子中的这些区域进行索引。函数 'replaceWithdash' 将 'word' 长度(总区域)替换为破折号。我不知道如何以某种方式按区域保持显示,但让 replaceWithdash 函数忽略或保持 spaces。输入:狗,吃了,食物。 当前显示:

 ------- --- --------
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"