首页 > 解决方案 > preg_replace( '/\h+/', ' ', $foo ) 在 JavaScript 中?

问题描述

如何删除多余的水平空格(空格和制表符)但保留 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

标签: javascript

解决方案


您可以使用同时包含制表符和空格的字符集:

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, ' ')
);


推荐阅读