在JavaScript中拆分字符串并检测换行符 [英] Split string in JavaScript and detect line break
问题描述
我有一个小函数,我发现从 textarea
,然后把它放入一个画布
元素,并且当线条过长时封装文本。但它不检测换行符。这是它正在做什么以及应该做什么:
I have a small function I found that takes a string from a textarea
and then puts it into a canvas
element and wraps the text when the line gets too long. But it doesn't detect line breaks. This is what it's doing and what it should do:
输入:
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);
}
是否可以实现我想要的?
Is it possible to achieve what I'm trying to get? Or is there a way to simply move the text area as is into the canvas?
推荐答案
使用以下命令:
var enteredText = document.getElementById("textArea").value;
var numberOfLineBreaks = (enteredText.match(/\n/g)||[]).length;
alert('Number of breaks: ' + numberOfLineBreaks);
DEMO
现在我所做的是先使用linebreaks拆分字符串,然后再次像之前一样拆分。注意:你也可以使用jQuery和regex结合使用:
DEMO
Now what I did was to split the string first using linebreaks, and then split it again like you did before. Note: you can also use jQuery combined with regex for this:
var splitted = $('#textArea').val().split("\n"); // will split on line breaks
希望能帮助你!
(注意:此问题已经问过一次 here )。
(Note: this question was already asked once here).
这篇关于在JavaScript中拆分字符串并检测换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!