在JavaScript字符串拆分和检测线断线DEMO

问题描述 投票:34回答:6

我有一个小功能,我发现需要从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);
}

是否有可能实现什么,我试图让?或者是有没有办法简单地移动文本面积是到画布?

javascript string canvas split line-breaks
6个回答
63
投票

使用以下命令:

var enteredText = document.getElementById("textArea").value;
var numberOfLineBreaks = (enteredText.match(/\n/g)||[]).length;
alert('Number of breaks: ' + numberOfLineBreaks);

DEMO

现在我所做的就是先分割字符串使用换行符,然后像之前一样再次分裂它。注意:您还可以使用jQuery结合正则表达式如下:

var splitted = $('#textArea').val().split("\n");               // will split on line breaks

希望可以帮助你!

(注:这个问题已经被问一次here)。


4
投票

如果你需要从你的JSON分割字符串,字符串有\ n特殊字符以\\ N置换的。

由换行符分割字符串:

Result.split('\n');

在JSON,其中特殊字符\ n被替换收到分割字符串\\ñJSON.stringify期间(在JavaScript)或json.json_encode(在PHP)。所以,如果你有你的AJAX响应字符串,它被加工运输。如果它没有被解码,它将窗台有\ n,其中\\ N置换的**,你需要使用:

Result.split('\\n');

请注意,从您的浏览器调试工具可能不会显示这个方面,因为你所期待的,但你可以看到,通过拆分\\ñ导致2项,因为我需要在我的情况:enter image description here


2
投票

在JavaScript字符串分割

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

要么

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

1
投票

这是我用来打印文本到画布上。输入不从textarea到来,但是从input和我的空间只有分裂。绝对不是完美的,但适合我的情况。它返回在数组行:

splitTextToLines: function (text) {
        var idealSplit = 7,
            maxSplit = 20,
            lineCounter = 0,
            lineIndex = 0,
            lines = [""],
            ch, i;

        for (i = 0; i < text.length; i++) {
            ch = text[i];
            if ((lineCounter >= idealSplit && ch === " ") || lineCounter >= maxSplit) {
                ch = "";
                lineCounter = -1;
                lineIndex++;
                lines.push("");
            }
            lines[lineIndex] += ch;
            lineCounter++;
        }

        return lines;
    }

0
投票

下面是我用[OP]的最终代码。也许不是最好的做法,但它的工作。

function wrapText(context, text, x, y, maxWidth, lineHeight) {

    var breaks = text.split('\n');
    var newLines = "";
    for(var i = 0; i < breaks.length; i ++){
      newLines = newLines + breaks[i] + ' breakLine ';
    }

    var words = newLines.split(' ');
    var line = '';
    console.log(words);
    for(var n = 0; n < words.length; n++) {
      if(words[n] != 'breakLine'){
        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;
        }
      }else{
          context.fillText(line, x, y);
          line = '';
          y += lineHeight;
      }
    }
    context.fillText(line, x, y);
  }

0
投票

你应该尝试检测第一线。

那么:

if(n == 0){
  line = words[n]+"\n";
}

我不知道,但也许它帮助。

© www.soinside.com 2019 - 2024. All rights reserved.