问题描述
如果一个人有一个 tab 大小为 2 个空格的 textarea,例如:
<textarea id="source">
function add(a,b,c) {
return a+b+c;
}
</textarea>
结果应该是:
<textarea id="source">
function add(a,c) {
return a+b+c;
}
</textarea>
有没有办法把它从2个空格转换成4个空格?
我正在尝试:
function convert(id,start,end) {
var myvalue = document.getElementById(id).value;
var myregex = new RegExp(" "*start,"g");
myvalue = myvalue.replace(myregex," "*end);
}
<textarea id="source">
function add(a,c) {
return a+b+c;
}
</textarea>
<button onclick="convert('source',2,4)">Convert Tab Size 2 => 4</button>
但是标签大小没有按预期转换。为什么?
解决方法
您不能在 javascript 中将字符串相乘。 例如,您可以使用 .repeat() 。 并且您没有将值放回元素中。只是更改 myvalue 不起作用,您必须将元素的值设置为 myvalue
function convert(id,start,end) {
var myvalue = document.getElementById(id).value;
var myregex = new RegExp(" ".repeat(start),"g");
myvalue = myvalue.replace(myregex," ".repeat(end));
document.getElementById(id).value = myvalue
}
<textarea id="source">
function add(a,b,c) {
return a+b+c;
}
</textarea>
<button onclick="convert('source',2,4)">Convert Tab Size 2 => 4</button>