Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I replace Space with %20 in javascript? [duplicate]

Tags:

javascript

Possible Duplicate:
jQuery / Javascript replace <space> in anchor link with %20

I am getting sParameter like this :

sParameter = document.getElementById('ddParameterType').value;

If I am getting word like "Test - Text" as the ddParameterType item, then I am replacing the space in word like below:

sParameter = document.getElementById('ddParameterType').value.replace("","%20");

but it is returning a valur like %20Test - Text.
I need like Test%20-%20Text.

like image 916
SDLBeginner Avatar asked Aug 27 '12 11:08

SDLBeginner


People also ask

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 double space in JavaScript?

“javascript double space” Code Answervar singleSpacesString=multiSpacesString. replace(/ +/g, ' ');//"I have some big spaces."

How do you remove double spacing in JavaScript?

Use JavaScript's string. replace() method with a regular expression to remove extra spaces. The dedicated RegEx to match any whitespace character is \s . Expand the whitespace selection from a single space to multiple using the \s+ RegEx.

How do I replace multiple spaces with single space?

The metacharacter “\s” matches spaces and + indicates the occurrence of the spaces one or more times, therefore, the regular expression \S+ matches all the space characters (single or multiple). Therefore, to replace multiple spaces with a single space.


2 Answers

sParameter = encodeURIComponent(sParameter.trim()) //"Test%20-%20Text" 

the .trim will remove leading and trailing whitespace from the string. encodeURIComponent will URL-encode it.

like image 148
Esailija Avatar answered Sep 22 '22 19:09

Esailija


replace replace("","%20"); with replace(/ /g,"%20");

http://www.w3schools.com/jsref/jsref_replace.asp

like image 32
user1546010 Avatar answered Sep 23 '22 19:09

user1546010