在 JavaScript 中拆分字符串并检测换行符

新手上路,请多包涵

我发现了一个小函数,它从 textarea 中获取一个字符串,然后将其放入一个 canvas 元素中,并在行变得太长时包装文本。但它不检测换行符。这就是它正在做的和应该做的:

输入:

Hello

This is dummy text that could be inside the text area.
It will then get put into the canvas.

错误的输出:

Hello this is dummy text
that could be inside the
text area. It will then
get put into the canvas.

它应该输出什么:

Hello

This is dummy text that
could be inside the text
area. It will then get
put into the canvas.

这是我正在使用的功能:

function wrapText(context, text, x, y, maxWidth, lineHeight) {
    var words = text.split(' ');
    var line = '';

    for(var n = 0; n < words.length; n++) {
        var testLine = line + words[n] + ' ';
        var metrics = context.measureText(testLine);
        var testWidth = metrics.width;
        if (testWidth > maxWidth && n > 0) {
            context.fillText(line, x, y);
            line = words[n] + ' ';
            y += lineHeight;
        }
        else {
            line = testLine;
        }
    }
    context.fillText(line, x, y);
}

是否有可能实现我想要得到的?或者有没有办法简单地将文本区域按原样移动到画布中?

原文由 Dustin Silk 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 677
2 个回答

使用 .split()

 var str = `your text
 that spans
 multiple lines`

 // Split the string on \n or \r characters
 var separateLines = str.split(/\r?\n|\r|\n/g);

 alert("Total number of separate lines is: " + separateLines.length);

或者使用 .match() 代替:

 var str = `your text
 that spans
 multiple lines`

 // Split the string on \n or \r characters
 var separateLines = str.match(/[^\r\n]+/g);

 alert("Total number of separate lines is: " + separateLines.length);

希望有帮助!

原文由 Jean-Paul 发布,翻译遵循 CC BY-SA 4.0 许可协议

在 JavaScript 中拆分字符串

var array = str.match(/[^\r\n]+/g);

要么

var array = str.split(/\r?\n/);

表现

原文由 Tính Ngô Quang 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题