Any expression that removes% 20 from a javascript string?

2

Example with javascript

var name = "Pedro Canche";
var newname = name.replace("%20", " ");
  

departure: Pedro Canche

but when it is like this:

var name = "Pedro Misael Canche Angulo";
var newname = name.replace("%20", " ");
  

exit: Pedro Misael% Canche% 20Angulo

I hope help, thank you.

    
asked by Pedro Misael Canche Angulo 05.03.2018 в 18:32
source

4 answers

6

The question does not make it clear if you want to add or remove %20 , but I think it's an interesting topic, so I answer in a global way:

There are several native methods in Javascript that are responsible for these transformations:

let baseURL='http://www.example.com/';
let otraURL='http://www.otra.com/'
let nombreFichero='espacio y carácter.txt';

//para codificar quitando caracteres especiales en una URL
console.log('Componiendo la URL:', encodeURI (baseURL+nombreFichero));

//para codificar parámetros, no la URI entera:
let param=encodeURIComponent(nombreFichero);
console.log('con parámetro:',baseURL + '?fichero=' + param );
//Aquí se ve la diferencia
param=encodeURIComponent(otraURL);
console.log('con una URL como parámetro:',baseURL + '?search=' + param );

console.log('Obteniendo nombre original: ', decodeURIComponent(param));
    
answered by 05.03.2018 в 19:34
2

Try this:

newname = name.replace(/%20/g," ");

with this it should work correctly.

    
answered by 05.03.2018 в 18:57
2

Try with

newname = name.replace(/%20/g," ");

I happened to place the g modifier to indicate that it replaces all the matches found on the string

    
answered by 05.03.2018 в 18:47
1

What you are using, is called encoding, basically the encoding allows you to use a character format in something transmissible by "internet"

Here you are using ASCII encoding,

You should not use replace, you should use the function to escape these characters if you want to:

in Javascript:

var name = "Pedro Misael%20Canche Angulo";

console.log(escape(name))

salida: Pedro%20Misael%2520Canche%20Angulo



console.log(unescape(name))

salida: Pedro Misael Canche Angulo
    
answered by 05.03.2018 в 19:36