将字符串的开头从 2 个空格转换为 4 个空格

问题描述

如果一个人有一个 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>

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...