【问题标题】:I want to reform this text我想修改这个文本
【发布时间】:2021-05-04 08:46:17
【问题描述】:

我想将下面的文本从01 j dh sish kdh sh j dhd 转换为01 j dh sish kdh sh j dhd

const reformText = '01    j    dh   sish  kdh          sh j   dhd     h  '

function textTransformer(text) {
if (!Array.isArray(text)) {

    let text2Arr = text.trim().split(' ')
    let pushArr = []
    let finalResult;

    text2Arr.map(function (item) {
        if (item.length !== 0) {
            pushArr.push(item)
        }
        finalResult = pushArr.join().replaceAll(',', '')
    })
    console.log(finalResult)
} else {
    alert('Your DATA STRUCTURE is An ARRAY')
}
}

textTransformer(reformText)

【问题讨论】:

  • 这对正则表达式很有用:用一个空格替换 \s+(= 一个或多个空白字符的序列)。
  • 该解决方案似乎很复杂,这种方法有什么原因吗?如果您只是删除多余的空格,text.trim().replace(/ +/g, " ") 会完成这项工作(对于空格,使用\s 而不是所有空格的空格)。 (好吧,text.trim().replace(/ {2,}/g, " ") 可能会更好。)
  • reformText.replace(/\s{2,}/g, " ")
  • 另外,map 不仅仅是一个迭代器。如果您不使用它创建的数组,请不要使用 map。在我的博客this post 中有详细信息。
  • 另外,如果你要加入一个带空格的数组,你可以使用.join(' '),而不是用逗号加入,然后将逗号更改为空格。

标签: javascript arrays string


【解决方案1】:

好吧,如果你真的想把事情复杂化,为什么不使用减速器呢?

const txt = "01    j    dh   sish  kdh          sh j   dhd     h  ";

const cleaned = txt
  .trim()
  .split("")
  .reduce( (acc, val) => 
    /\s{2,}/.test(`${acc[acc.length-1]+val}`) ? acc : [...acc, val],  [])
  .join("");

console.log(`[${cleaned}]`);

// for the record
console.log(`[${txt.trim().replace(/\s+/g, " ")}]`);

【讨论】:

    猜你喜欢
    • 2019-07-27
    • 2019-12-17
    • 1970-01-01
    • 2014-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-27
    • 2012-02-22
    相关资源
    最近更新 更多