javascript function replace

3

From the following function, how do I substitute blank spaces with hyphens?

<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="utf-8" />
<title>Ej funciones</title>
</head> 
<body>
<script type="text/javascript">


var texto=prompt ("Introduce el texto");

function espaciosEnBlanco() {
var sustituye=texto.split(" ");
var operacion=texto.replace(sustituye, "-");

alert(operacion);

}

espaciosEnBlanco();



</script>
</body>
</html>
    
asked by user09b 25.10.2018 в 18:21
source

2 answers

4

You do not need the split . Only with replace works like this:

<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="utf-8" />
<title>Ej funciones</title>
</head> 
<body>
<script type="text/javascript">

var texto=prompt ("Introduce el texto");

function espaciosEnBlanco() {
  var operacion=texto.replace(/\s/g, "-");

  alert(operacion);

}

espaciosEnBlanco();

</script>
</body>
</html>
    
answered by 25.10.2018 в 18:24
3

There are several ways to do the same:

<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="utf-8" />
<title>Ej funciones</title>
</head> 
<body>
<script type="text/javascript">

var texto = prompt ("Introduce el texto");

function espaciosEnBlanco1() {
  var operacion=texto.replace(/\s/g, '-');

  console.log(operacion);

}
function espaciosEnBlanco2() {
  var operacion=texto.split(' ').join('-');

  console.log(operacion);

}

function espaciosEnBlanco3() {
  let operacion=texto;
  while(operacion.indexOf(' ') >-1) {
    operacion=operacion.replace(' ','-');
  }

  console.log(operacion);

}

espaciosEnBlanco1();
espaciosEnBlanco2();
espaciosEnBlanco3();

</script>
</body>
</html>
    
answered by 25.10.2018 в 18:57