【问题标题】:Regex who matches only whitespacs not tab, a carriage return or lie feed in Javascript [duplicate]仅匹配空格而不匹配制表符的正则表达式,Javascript中的回车符或换行符[重复]
【发布时间】:2020-09-02 02:54:08
【问题描述】:

我想格式化一个没有多个空格的字符串。字符串可以有制表符、回车符或换行符。

示例 1: hello world 预期结果:hello world

示例 2:hello world 预期结果:'hello world'

const formatString = (s) => {
  const trimmed = s.trim();
  const formated = trimmed.match(/\s/g)
  return s.trim().replace(/\s+/g, ' ')
}

const str = `hello
world`
const result = formatString(str)
console.log(result)

【问题讨论】:

    标签: javascript regex


    【解决方案1】:

    您可以使用空间(确切的空间)。更容易

    const formatString = (s) => {
      return s.replace(/ +/g, " ");
    };
    
    let str = `hello
    world`;
    const result = formatString(str);
    console.log(result);
    str = `hello    world`;
    
    console.log(formatString(str));

    使用正则表达式:

    const formatString = (s) => s.replace(/[^\S\r\n]+/g, " ");
    
    console.log(
      formatString(`hello
    world`)
    );
    console.log(formatString(`hello     world`));

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-12
      • 1970-01-01
      • 1970-01-01
      • 2023-01-02
      • 2014-06-30
      • 1970-01-01
      • 1970-01-01
      • 2011-10-23
      相关资源
      最近更新 更多