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
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
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>
One possible way to achieve this is:
"-"
separator using Array.join ()
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));
With a single replace:
cadena = cadena.replace(/(.)(?!$)\s*/ug,'$1-');