Dus*_*ilk 40 javascript string split canvas line-breaks
我有一个小函数,我发现它从a中取一个字符串textarea,然后将它放入一个canvas元素中,并在行变得太长时包装文本.但它没有检测到换行符.这就是它正在做的事情以及应该做的事情:
输入:
Hello
This is dummy text that could be inside the text area.
It will then get put into the canvas.
Run Code Online (Sandbox Code Playgroud)
输出错误:
Hello this is dummy text
that could be inside the
text area. It will then
get put into the canvas.
Run Code Online (Sandbox Code Playgroud)
它应该输出什么:
Hello
This is dummy text that
could be inside the text
area. It will then get
put into the canvas.
Run Code Online (Sandbox Code Playgroud)
这是我正在使用的功能:
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);
}
Run Code Online (Sandbox Code Playgroud)
是否有可能实现我想要的目标?或者有没有办法简单地将文本区域移动到画布中?
Jea*_*aul 67
使用以下内容:
var enteredText = document.getElementById("textArea").value;
var numberOfLineBreaks = (enteredText.match(/\n/g)||[]).length;
alert('Number of breaks: ' + numberOfLineBreaks);
Run Code Online (Sandbox Code Playgroud)
现在我所做的是首先使用换行符拆分字符串,然后再像之前那样拆分它.注意:您也可以将jQuery与regex结合使用:
var splitted = $('#textArea').val().split("\n"); // will split on line breaks
Run Code Online (Sandbox Code Playgroud)
希望能帮到你!
(注意:此问题已在此处提出过一次).
Tín*_*ang 32
JavaScript 中的拆分字符串
var array = str.match(/[^\r\n]+/g);
Run Code Online (Sandbox Code Playgroud)
或者
var array = str.split(/\r?\n/);
Run Code Online (Sandbox Code Playgroud)
如果您需要从JSON拆分字符串,则该字符串会将\ n特殊字符替换为\\ n。
用换行符分割字符串:
Result.split('\n');
Run Code Online (Sandbox Code Playgroud)
在JSON中收到的拆分字符串,其中在JSON.stringify(在javascript中)或json.json_encode(在PHP中)期间,特殊字符\ n被\\ n替换。因此,如果您的字符串包含在AJAX响应中,则将其处理以进行运输。如果未解码,则将\ n替换为\\ n **,并且您需要使用:
Result.split('\\n');
Run Code Online (Sandbox Code Playgroud)
请注意,浏览器中的调试器工具可能未如您期望的那样显示此方面,但是您可以看到按\\ n拆分会产生2个条目,这是我需要的:

| 归档时间: |
|
| 查看次数: |
156806 次 |
| 最近记录: |