代码之家  ›  专栏  ›  技术社区  ›  SeaBass

JavaScript中的preg\u replace('/\h+/','',$foo)?

  •  2
  • SeaBass  · 技术社区  · 7 年前

    如何在javascript中删除多余的水平空格(空格和制表符),但保留换行符?

    使用PHP: preg_replace( '/\h+/', ' ', $foo )

    A   lot   of   text text   text     text
    A lot more  text     text text     text       text
    

    应该是这样的:

    A lot of text text text text
    A lot more text text text text text
    
    4 回复  |  直到 7 年前
        1
  •  3
  •   CertainPerformance    7 年前

    const str = `A   lot   of			text text   text     text
    And more  text     text text     text         text`;
    console.log(
      str.replace(/[ 	]+/g, ' ')
    );

    或者,用 \t 改为元字符:

    const str = `A   lot   of			text text   text     text
    And more  text     text text     text         text`;
    console.log(
      str.replace(/[ \t]+/g, ' ')
    );
        2
  •  1
  •   vol7ron    7 年前

    你可以用双负片 /[^\S\n]+/ 要查找不是换行符的空白字符,请执行以下操作:

    let str = `A   lot   of   text text   text     text
    A lot more  text     text text     text       text`
    console.log('before:',str)
    
    // use a double negative (not a word character or newline)
    str = str.replace(/[^\S\n]+/g,' ')
    console.log('after:',str)

    \S ,但这可能比目前列出的所有其他答案都安全。

        3
  •  0
  •   Kai    7 年前

    const str = `A   lot   of			text text   text     text
    And more  text     text text     text         text`;
    
    console.log(
      str.replace(/[ \t]{2,}/g, ' ')
    );
        4
  •  0
  •   Calvin    7 年前
    outp = str.replace(/[ \t]+/g,' ');
    

    此过滤器会过滤所有额外的间距和制表符