Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript replace query string + with a space

I'm grabbing the query string parameters and trying to do this:

var hello = unescape(helloQueryString); 

and it returns:

this+is+the+string

instead of:

this is the string

Works great if %20's were in there, but it's +'s. Any way to decode these properly so they + signs move to be spaces?

Thanks.

like image 809
BruceClark Avatar asked May 27 '10 03:05

BruceClark


People also ask

How do you replace a string with spaces?

Approach: In the given string Str, replace all occurrences of Sub with empty spaces. Remove unwanted empty spaces in start and end of the string. Print the modified string.

Can query strings have spaces?

According to the W3C (and they are the official source on these things), a space character in the query string (and in the query string only) may be encoded as either " %20 " or " + ".

How do you replace a space in Javascript?

Use the String. replace() method to replace all spaces in a string, e.g. str. replace(/ /g, '+'); . The replace() method will return a new string with all spaces replaced by the provided replacement.

How do you replace a space in react?

In the above code, we have passed two arguments to the replace() method first one is regex /\s/g and the second one is replacement value + , so that the replace() method will replace all-white spaces with a + sign. The regex /\s/g helps us to remove the all-white space in the string.


2 Answers

The decodeURIComponent function will handle correctly the decoding:

decodeURIComponent("this%20is%20the%20string"); // "this is the string"

Give a look to the following article:

  • Comparing escape(), encodeURI(), and encodeURIComponent()
like image 178
Christian C. Salvadó Avatar answered Sep 24 '22 21:09

Christian C. Salvadó


Adding this line after would work:

hello = hello.replace( '+', ' ' );
like image 29
Kerry Jones Avatar answered Sep 23 '22 21:09

Kerry Jones