[英]Add an ' at the beggining of each line and remove the comma on the last line
我有以下代码:
function addComma() { // get textarea's content var content = document.getElementById('myTextArea').value; // replace all newline's with ';\\n' var replaced = content.replace(/\\n/g, '\\',\\n'); // rewrite the content with the new content document.getElementById('myTextArea').value = replaced; }
<textarea id='myTextArea' rows='5' cols='30'> First Line Second Line Third Line </textarea> <input type='button' onclick='addComma()' value='Add Comma' />
我如何在每行的开头添加一个'但要删除最后一行的逗号。 (我将有三排以上。)
提前致谢!
我认为这是一种略有不同的方法,可以为您提供所需的结果:
var replaced = content.split('\n').map(l => "'" + l + "'").join(',\n')
这样做是将内容分割成一个数组(通过新行), map
函数将基本上遍历每一行,并在开始和结尾处添加',最后join
将使用逗号将数组重新组合成字符串,然后新队
我的过滤器确保没有空行; 无需子字符串摆弄。
var replaced = content.split('\n').filter(p=>p!="").map(p=>'\''+p).join(',\n');
使用split
和map
:
function addComma() { var content = document.getElementById('myTextArea').value; //Add in commas and speech marks var replaced = content.split("\\n").map(e => `'${e}',`).join("\\n"); //Remove last comma replaced = replaced.substring(0, replaced.length - 1); //Put text back into page document.getElementById('myTextArea').value = replaced; }
<textarea id='myTextArea' rows='5' cols='30'> First Line Second Line Third Line</textarea> <input type='button' onclick='addComma()' value='Add Comma' />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.