1

如果一个人有一个标签大小为 2 个空格的文本区域,例如:

<textarea id="source">
function add(a,b,c) {
  return a+b+c;
}
</textarea>

结果应该是:

<textarea id="source">
function add(a,b,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,b,c) {
  return a+b+c;
}
</textarea>
<button onclick="convert('source',2,4)">Convert Tab Size 2 => 4</button>

但是标签大小没有按预期转换。为什么?

4

1 回答 1

1

你不能在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>

于 2021-05-02T21:42:36.730 回答