在 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);
}

有可能达到我想要的效果吗?或者有一种方法可以简单地将文本区域移动到画布中?

288108 次浏览

Using .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);

Or using .match() instead:

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

Hope that helps!

You should try detect the first line.

Then the:

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

I'm not sure, but maybe it helps.

Here's the final code I [OP] used. Probably not best practice, but it worked.

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

This is what I used to print text to a canvas. The input is not coming from a textarea, but from input and I'm only splitting by space. Definitely not perfect, but works for my case. It returns the lines in an array:

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;
}

In case you need to split a string from your JSON, the string has the \n special character replaced with \\n.

Split string by newline:

Result.split('\n');

Split string received in JSON, where special character \n was replaced with \\n during JSON.stringify(in javascript) or json.json_encode(in PHP). So, if you have your string in a AJAX response, it was processed for transportation. and if it is not decoded, it will sill have the \n replaced with \\n** and you need to use:

Result.split('\\n');

Note that the debugger tools from your browser might not show this aspect as you was expecting, but you can see that splitting by \\n resulted in 2 entries as I need in my case: enter image description here

Split string in JavaScript

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

OR

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

Performance

You can use the split() function to break input on the basis of line break.

yourString.split("\n")