Peter
Peter

Reputation: 685

replace / with "" and " " with %20 in one go on a javascript variable?

I insert some strings in an array but before I do that I want to do what topic says. To only replace space with %20 I do:

Name.push(linkText.replace(" ", "%20"));

But how do I perform two "replace" there in one go?

Thanks in advance

Upvotes: 2

Views: 421

Answers (4)

RMorrisey
RMorrisey

Reputation: 7739

It looks to me like you are trying to encode plaintext to use it in a URL or query string. I suspect you would be better off using one of javascript's built-in encoding methods, encodeURI or encodeURIComponent. See:

http://www.javascripter.net/faq/escape.htm

Upvotes: 2

Dumb Guy
Dumb Guy

Reputation: 3446

You can't do it using a single function call in regular JavaScript.

You could do this:

Name.push(linkText.replace(" ", "%20").replace("/", ""));

Upvotes: 0

Andrew Cooper
Andrew Cooper

Reputation: 32586

You could do something like this:

Name.push(linkText.replace(" ", "%20").replace("/", ""));

Upvotes: 0

jtbandes
jtbandes

Reputation: 118741

Do you want to replace two spaces in a row with one %20?

Name.push(linkText.replace(/ +/g, "%20"));

Or do you want to replace 2 spaces with %20%20?

Name.push(linkText.replace(/ /g, "%20"));

Upvotes: 0

Related Questions