And*_*cer 3 javascript regex indentation line-breaks
我正在处理网站后端的文本输入。我希望自动更正一些事情。例如,我将 textarea 中的新行转换为<br>. 我还想让用户在新行上切换。
这需要将空格更改为 . 我只想转换位于新行开头的空格。例如,假设用户将其输入到 textarea 中:
This is my text! It's pretty great.
This is a second line.
This is a third line, that is indented by four spaces.
This is a fourth line.
Run Code Online (Sandbox Code Playgroud)
使用正则表达式,我得到了每一行的第一个空格进行转换:
.replace(/^[ ]/mg,' ');
Run Code Online (Sandbox Code Playgroud)
我有多个空格可以转换为一个空格:
.replace(/[ ]{2,}/mg,' ');
Run Code Online (Sandbox Code Playgroud)
我不知道如何转换所有四个缩进空格。我已经在互联网上搜索了大约 3 个小时,我找到了类似的答案,但没有什么是我可以在这里工作的。有什么想法吗?
function escapeSpaces(str) {
var regex = /^ +/mg;
return str.replace(regex, function (match) {
var result = "";
for (var i = 0, len = match.length; i < len; i++) {
result += " ";
}
return result;
});
}
Run Code Online (Sandbox Code Playgroud)
这可能不是最好的解决方案,但它有效。
或者:
function escapeSpaces (str) {
return str.replace(/^ +/mg, function (match) {
return match.replace(/ /g, " ");
});
}
Run Code Online (Sandbox Code Playgroud)