如何让 Java Script 忽略或维护空格,而不是删除它们 [英] How to make Java Script ignore or maintain spaces, not delete them

查看:31
本文介绍了如何让 Java Script 忽略或维护空格,而不是删除它们的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让一个函数用破折号覆盖多词区域,但不包括在 Java Script 中用破折号覆盖单词之间的空间.所以,我基本上需要 JS 来忽略空格(或者维护?)但我在网上找到的只是如何从字符串中删除空格.如果我这样做,那么覆盖该区域的破折号之间仍然不会有空格(尽管从技术上讲,如果没有空格,它将是正确的长度).这是我正在使用的功能:开始例程:

I'm trying to have a function cover a multi-word region with dashes, but not cover the space between the words with a dash in Java Script. So, I basically need JS to ignore the spaces (or maintain then?) but all I've found online is how to remove spaces from a string. If I do that, then there will still be no spaces between the dashes covering the region (though it would technically be the correct length without the space). This is the function I'm working with for this: Begin Routine:

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 函数忽略或保留空格.输入:狗,吃了,食物.当前显示:

Regions are separated by the delimiter "," so that multiple words can be included. The variable "word" basically indexes through these regions in the sentence. The function 'replaceWithdash' replaces the 'word' length (total region) with dashes. I don't know how to somehow keep the display as region by region but have the replaceWithdash function ignore or maintain spaces. Input: The dog, ate, the food. Current display:

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

所需的显示:

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

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

Does anyone know a way around this?

推荐答案

如果我理解正确,这就是您要找的,对吗?

If I understood correctly, this is what you are looking or, right?

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"

这篇关于如何让 Java Script 忽略或维护空格,而不是删除它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆