将多个空格转换为& nbsp;在Javascript开头 [英] Convert Multiple Spaces to   At Beginning of Line with Javascript

查看:103
本文介绍了将多个空格转换为& nbsp;在Javascript开头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为网站后端的文本输入工作。我想要一些事情自动纠正。例如,textarea中的新行我转换为< br> 。我还想让用户选中新行。

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.

这需要将空格更改为& nbsp; 。我只想转换位于新行开头的空格。例如,假设用户将其键入textarea:

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;');

我无法弄清楚如何转换所有这四个缩进空格。我已经在互联网上搜索了大约3个小时,我找到了类似的答案,但我没办法在这里工作。有什么想法?

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?

推荐答案

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.

或者:

function escapeSpaces (str) {
    return str.replace(/^ +/mg, function (match) {
        return match.replace(/ /g, "&nbsp;");
    });
}

这篇关于将多个空格转换为&amp; nbsp;在Javascript开头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆