Skip to content
Advertisement

Convert start of String from 2 spaces to 4 spaces

If a person has a textarea with a tab size of 2 spaces, such as this:

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

The result should be:

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

Is there a way to convert it from 2 spaces to 4 spaces?

I am trying this:

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>

But the tab size does not convert as expected. Why?

Advertisement

Answer

You can’t multiply strings in javascript. you can use .repeat() for example. and you didn’t put the value back into the element. just changing myvalue doesn’t work, you have to set the element’s value to 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>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement