我的问题很简单,但我无法弄清楚。我有一个简单的表单(文本区域),用户在其中输入一些文本,并将该文本保存在数据库中。问题是 - 我想在保存文本之前删除不必要的空格。所以我创建了一个简单的 Javascript 函数:
str.replace(/\n\s*\n\s*\n/g, '\n');
但是当用户发布如下文本时,它不会删除空格:
hello world \nanother sample \n test
(因此,当用户在最后一个单词后添加一个/多个空格,然后在新行中发布另一个单词时,这些空格将被保留(并保存在数据库中):
hello word <br>another sample <br> test
等等
我需要的是 JavaScript 删除这些空格后跟新行,以便结果是:
hello word<br>another sample<br>test
最佳答案
只需要简化你的正则表达式:
const input = 'hello world \nanother sample \n test';
const output = input
// Remove all whitespace before and after a linebreak
.replace(/\s*\n\s*/g, '\n');
console.log(output);
或者,如果您想查看它,因为它将保存在您的数据库中:
const input = 'hello world \nanother sample \n test';
const output = input
// Remove all whitespace before and after a linebreak
.replace(/\s*\n\s*/g, '<br>');
console.log(output);
关于Javascript - 删除紧跟换行符的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44658717/