【问题标题】:How to make Java Script ignore or maintain spaces, not delete them如何让 Javascript 忽略或保持空间,而不是删除它们
【发布时间】:2021-08-13 06:01:59
【问题描述】:

我试图让一个函数用破折号覆盖一个多词区域,但在 Java Script 中用破折号覆盖单词之间的空间。所以,我基本上需要 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”用破折号替换“单词”长度(总区域)。我不知道如何以某种方式将显示保持为一个区域一个区域,但让 replaceWithdash 函数忽略或保持空格。输入:狗,吃了,食物。 当前显示:

 ------- --- --------
The dog --- --------

想要的显示:

 --- --- --- --- ----
The dog --- --------

有人知道解决这个问题的方法吗?

【问题讨论】:

  • 请提供句子输入吗?
  • 在 csv 文件中输入的句子是这样的:The dog, ate, the food。我还尝试在诸如下划线之类的单词之间使用不同的分隔符,以便输入为:The_dog、_ate、_the_food。但这实际上并没有解决任何问题,因为 JS 仍然将下划线读取为字符。
  • 所以你希望The dog, ate, the food--- --- --- --- ----
  • 是的,没错!但我需要的不是逐字显示,而是逐个区域(多字)。与 replaceWithdash 的输入句子混淆并不能成功地做到这一点(如更改分隔符等),所以我试图做的不是让 replaceWithdash 将单词之间的空格读取为字符并将它们保留为空格。
  • But i need the display to not be word by word, instead to be region (mulit-word) by region. 到底是什么意思?

标签: javascript string for-loop str-replace spaces


【解决方案1】:

如果我理解正确,这就是你正在寻找的,对吧?

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"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-15
    • 1970-01-01
    • 2015-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多