我有以下代码:
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
将使用逗号和换行符将数组连接回字符串
关于javascript - 在每行开头添加 ' 并删除最后一行的逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55347732/