How to enter - between characters of a string in JavaScript?

2

Having the following string:

var cadena = "Hola que tal estas";

I wanted to know how it can be shown separated by dashes, that is:

var cadena = "H-o-l-a-q-u-e-t-a-l-e-s-t-a-s
    
asked by Stewie 21.10.2017 в 23:30
source

3 answers

3

Can be achieved using String.replace(regex, replacement) , Array.split and Array.join() .

First we have to eliminate the blank spaces and for that we use replace and then we separate each character with the split () method and then we join it with the join () method using the - as a separator:

function convertir()
{
  var input = document.getElementById("texto").value;
  console.log(input.replace(/\s/g, '').split('').join('-'));
}
<input type="text" id="texto" />

<button onclick="convertir()">Convertir</button>
    
answered by 21.10.2017 / 23:46
source
2

One possible way to achieve this is:

  • Replace spaces using String.replace () as they are not part of the final result
  • Obtain an array with all the characters of the string using Array.from ()
  • Join the elements of the character array with the "-" separator using Array.join ()
  • Return the result of the previous operation.

let convertString = (aString) => {
   return Array.from(aString.replace(/\s/g, '')).join("-");
}

const cadena = "Hola que tal estas";
console.log(convertString(cadena));

Another way is to use Array.filter () to discard spaces and Array.join () to join with "-"

let convertString = (aString) => {
   return Array.from(aString).filter((item)=>{
      return item !== " ";
   }).join("-");
}

const cadena = "Hola que tal estas";
console.log(convertString(cadena));
    
answered by 21.10.2017 в 23:46
0

With a single replace:

cadena = cadena.replace(/(.)(?!$)\s*/ug,'$1-');
    
answered by 26.11.2017 в 12:18