问题
I'm working on a text input for the backend of a website. I want a couple things to be automatically corrected. Example, new lines in the textarea I convert to <br>
. I also want to let the user tab over on new lines.
This requires changing spaces over to
. I only want to convert spaces that are at the start of a new line though. Example, say the user types this into a 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.
Using regex, I've gotten the first space on each line to convert:
.replace(/^[ ]/mg,' ');
I've gotten multiple spaces to convert to one space:
.replace(/[ ]{2,}/mg,' ');
I can't figure out how to convert all four of those indenting spaces though. I've been scouring the internet for about 3 hours, and I've found similar answers, but nothing that I could get to work here. Any thoughts?
回答1:
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;
});
}
This may not be the best solution, but it works.
Alternatively:
function escapeSpaces (str) {
return str.replace(/^ +/mg, function (match) {
return match.replace(/ /g, " ");
});
}
来源:https://stackoverflow.com/questions/15815256/convert-multiple-spaces-to-nbsp-at-beginning-of-line-with-javascript