限制多个换行符、限制双倍空格、正则表达式替换

问题描述 投票:0回答:1

我在限制字符串以防止多个空格和多个换行符时遇到问题。 在上传到服务器之前,输入值将发生这种重新格式化。

例如:

----
Input:
----
    i am    a   text
with

little



to no


meaning    asdas

----
Expected output:
----
i am a text
with

little

to no

meaning asdas

我用谷歌搜索了这个,但它只对换行有帮助。

str.replace(/\n\s*\n/g, '\n\n')
javascript regex replace newline whitespace
1个回答
0
投票

首先将超过 2 个换行符替换为正好 2 个换行符,然后将多个空格替换为一个空格?

var t = `
i am    a   text
with

little



to no


meaning    asdas
`.trim();
console.log(t.replace(/\n{2,}/g, '\n\n').replace(/[ ]{2,}/g, ' '));

© www.soinside.com 2019 - 2024. All rights reserved.