Convert Multiple Spaces to   At Beginning of Line with Javascript

空扰寡人 提交于 2019-12-10 17:52:00

问题


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

I've gotten multiple spaces to convert to one space:

.replace(/[ ]{2,}/mg,'&nbsp;');

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 += "&nbsp;";
        }
        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, "&nbsp;");
    });
}


来源:https://stackoverflow.com/questions/15815256/convert-multiple-spaces-to-nbsp-at-beginning-of-line-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!