I'm doing some more advanced automation on iOS devices and simulators for an enterprise application. The automation is written in browserless Javascript. One of the methods works on the device but not on the simulator, so I need to code a workaround. For the curious, it's UIATarget.localTarget().frontMostApp().preferencesValueForKey(key).
What we need to do is read a path to a server (which varies) from a plist file on disk. As a workaround on the simulator, I've used the following lines to locate the plist file containing the preferences:
// Get the alias of the user who's logged in
var result = UIATarget.localTarget().host().performTaskWithPathArgumentsTimeout("/usr/bin/whoami", [], 5).stdout;
// Remove the extra newline at the end of the alias we got
result = result.replace('\n',"");
// Find the location of the plist containing the server info
result = UIATarget.localTarget().host().performTaskWithPathArgumentsTimeout("/usr/bin/find", ["/Users/"+result+"/Library/Application Support/iPhone Simulator", "-name", "redacted.plist"], 100);
// For some reason we need a delay here
UIATarget.localTarget().delay(.5);
// Results are returned in a single string separated by newline characters, so we can split it into an array
// This array contains all of the folders which have the plist file under the Simulator directory
var plistLocations = result.stdout.split("\n");
...
// For this example, let's just assume we want slot 0 here to save time
var plistBinaryLocation = plistLocations[0];
var plistXMLLocation = plistLocations[i] + ".xml";
result = UIATarget.localTarget().host().performTaskWithPathArgumentsTimeout("/usr/bin/plutil", ["-convert","xml1", plistBinaryLocation,"-o", plistXMLLocation], 100);
From here, I think the best way to get the contents is to cat or grep the file, since we can't read the file directly from disk. However, I'm having trouble getting the syntax down. Here's an edited snippet of the plist file I'm reading:
<key>server_url</key>
<string>http://pathToServer</string>
There are a bunch of key/string pairs in the file, where the server_url key is unique. Ideally I'd do something like a lookback, but because JavaScript doesn't appear to support it, I figured I'd just get the pair from the file and whittle it down a bit later.
I can search for the key with this:
// This line works
var expression = new RegExp(escapeRegExp("<key>server_url</key>"));
if(result.stdout.match(expression))
{
UIALogger.logMessage("FOUND IT!!!");
}
else
{
UIALogger.logMessage("NOPE :(");
}
Where the escapeRegExp method looks like this:
function escapeRegExp(str)
{
var result = str.replace(/([()[{*+.$^\\|?])/g, '\\$1');
UIALogger.logMessage("NEW STRING: " + result);
return result;
}
Also, this line returns a value (but gets the wrong line):
var expression = new RegExp(escapeRegExp("<string>(.*?)</string>"));
However, when you put the two together, it (the Regex syntax) works on the terminal but doesn't work in code:
var expression = new RegExp(escapeRegExp("<key>server_url</key>[\s]*<string>(.*?)</string>"));
What am I missing? I also tried grep and egrep without any luck.
There are two problems affecting you here getting the regex to work in your JavaScript code.
First, you are escaping the whole regex expression string, which means that your capturing (.*?) and your whitespace ignoring [\s]* will also be escaped and won't be evaluated the way you're expecting. You need to escape the XML parts and add in the regex parts without escaping them.
Second, the whitespace ignoring part, [\s]* is falling prey to JavaScript's normal string escaping rules. the "\s" is turning into "s" in the output. You need to escape that backslash with "\s" so that it stays as "\s" in the string that you pass to construct the regular expression.
I've built a working script that I've verified in the UI Automation engine itself. It should extract and print out the expected URL:
var testString = "" +
"<plistExample>\n" +
" <key>dont-find-me</key>\n" +
" <string>bad value</string>\n" +
" <key>server_url</key>\n" +
" <string>http://server_url</string>\n" +
"</plistExample>";
function escapeRegExp(str)
{
var result = str.replace(/([()[{*+.$^\\|?])/g, '\\$1');
UIALogger.logMessage("NEW STRING: " + result);
return result;
}
var strExp = escapeRegExp("<key>server_url</key>") + "[\\s]*" + escapeRegExp("<string>") + "(.*)" + escapeRegExp("</string>");
UIALogger.logMessage("Expression escaping only the xml parts:" + strExp);
var exp = new RegExp(strExp);
var match = testString.match(exp);
UIALogger.logMessage("Match: " + match[1]);
I should point out, though, that the only thing you need to escape in the regex is the forward slashes in the XML closing tags. That means that you don't need your escapeRegExp() function and can write the expression you want like this:
var exp = new RegExp("<key>server_url<\/key>[\\s]*<string>(.*)<\/string>");
I've seen several results for removing characters after a specific character - my question is how would I do that with a string?
Basically, this applies to any given string of data, but let's take a URL: stackoverflow.com/question
With given string, and in JS, I'd like to remove everything after ".com", assign ".com" to a variable, and assign the text before ".com" to a separate variable.
So, end result: var x = "stackoverlow" var y = ".com"
What I've done so far:
1) Using a combination of split, substring, etc. I can get it to remove pieces, but not without removing part of the ".com" string. I'm pretty sure I can do what I want to do with substring and split, I think I'm just implementing it incorrectly.
2) I'm using indexOf to find the string ".com" within the full string
Any tips? I haven't posted my actual code because it's become so garbled with all the different things I've tried (I can go ahead and do so if necessary).
Thanks!
You should really look into Regular Expressions.
Here is some code that can get what you are trying to do:
var s = 'stackoverflow.com/question';
var re = /(.+)(\.com)(.+)/;
var result = s.match(re);
if (result && result.length >= 3) {
var x = result[1], //"stackoverlow"
y = result[2]; //".com"
console.log('x: ' + x);
console.log('y: ' + y);
}
Use regular expressions.
"stackoverflow.com".match(/(.+)(\.com)/)
results in
["stackoverflow.com", "stackoverflow", ".com"]
(Why would you want to assign .com to a variable, though?
"stackoverflow.com".split(/\b(?=\.)/) => ["stackoverflow", ".com"]
Or,
"stackoverflow.com/question".split(/\b(?=\.)|(?=\/)/)
=> ["stackoverflow", ".com", "/question"]
I have the following expression to validate a URL but it gives me a syntax error on the browser. I am no expert in regex expressions so I am not sure what I am looking for. I would also like it to test for http:// and https:// urls.
"url":{
"regex":"/^http\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(/\S*)?$/",
"alertText":"URL must start with http://"}
Edit:
To clarify I am looking for help for both the regex and the syntax issues please. I have tried about 20 different variations based on all the answers but still no luck. Just to clarity, I do not need to validate the entire URL. I just need to validate that it starts with http:// or https:// but it must not fail validation if left empty. I can get the http part working with this
/^https?:///
no need to escape the / even. But it fails if the input field is empty, when I try:
/^(https?://)?/
I get an error saying "unterminated parenthetical /^(https?://)/".
Just to confuse matters more, here is one that I added yesterday to validate a date or no entry and it like the same sort of format to me.
/^([0-9]{1,2}\-\[0-9]{1,2}\-\[0-9]{4})?$/
For what it's worth, the syntax error is the unescaped forward slash here: /\S*
Edit: oh wow, I'm tired. All of the forward slashes are unescaped. You can escape them with a backslash: \/
Here's the spec on URIs, of which URLs are a subset, or here's the spec on URLs if you're sure that's all you care about. A full implementation of either would be nearly impossible with only a single regular expression.
If you truly want to validate a URL, one that you know will be HTTP or HTTPS, send it an HTTP HEAD request and check the response code.
Alternatively, if you're going to play loose with the spec, decide how loose you're willing to be with the input, and if it's better to exclude valid URLs or permit false ones.
If you want to test for a URL or empty input, you might want to do two passes.
test for empty string.
test for valid url.
I would do something like the following (assuming urlString is my input).
// get rid of whitespace, in case user hit spacebar/tab
// also removes leading/trailing spaces.
urlString = urlString.replace(/[\s]*/g,'');
// test if zero length string, if not, test the url.
if( urlString.length > 0 ){ // test the URL
var re = new RegExp( your_expression_goes_here );
var result = re.exec(urlString);
if( result != null ) {
// we have a hit!!! this is a URL.
} else {
// this is a bad string.
}
} else {
// user entered no text, let's move on.
}
So, the preceding should work and allow you to test for either empty string or a url. As to the regular expression you're using "/(http|https):///", I believe it's a bit flawed. Yes, it will catch "http://" or "https://", but it will also key in on a string like "htthttp://" which is clearly not what you want.
Your other sample "/^(http|https):///" is better in that it will match from the beginning of the string and will tell you if the string begins like a URL.
Now, I think jrob above was on the right track with his second string in regards to testing the full URL. I think I found the same sample he used at this page. I've modified the expression as per below and tested it using an online regex tester, can't post the link as I'm a new user :D.
It seems to catch a whole manner of valid URLs and produces an error if the input string is in any way an invalid URL, at least for the invalid URLs I can think of. It also catches http/https protocols only, which I think is your base requirement.
^(?:http(?:s?)\:\/\/|~/|/)?(?:\w+:\w+#)?(?:(?:[-\w]+\.)+([a-zA-Z]{2,9}))(?::[\d]{1,5})?(?:(?:(?:/(?:[-\w~!$+|.,=]|%[a-f\d]{2})+)+|/)+|\?|#)?(?:(?:\?(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)(?:&(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)*)*(?:#(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)?$
Hope this helps.
Updated code (twice).
I still strongly suggest you test for empty string first as per my earlier example, and you only test for the valid values if the string is non zero. I have tried to combine the two tests into one, but have been unable to do so so far (maybe someone else can still figure it out).
The following tests work for me, here's a URL sample as you required:
//var re = /^(?:http(?:s?)\:\/\/)/;
// the following expression will test for http(s):// and empty string
var re = /^(?:http(?:s?)\:\/\/)*$/;
// use the precompiled expression above, or the following
// two lines:
//var reTxt = "^(?:http(?:s?)\:\/\/)";
//var re = new RegExp(reTxt);
alert(
"result:" + re.test("http://") +
"\nresult:" + re.test("https://") +
"\nresult:" + re.test("") +
"\nresult:" + re.test("https:") +
"\nresult:" + re.test("xhttp://") +
"\nresult:" + re.test("ftp://") +
"\nresult:" + re.test("http:/") +
"\nresult:" + re.test("http://somepage.com") +
"\nresult:" + re.test("httphttp://") +
"\nresult:" + re.test(" http://") +
"\nresult:" + re.test("Random text")
);
And here's a test for dates:
var re2 = /^[0-9]{1,2}\-[0-9]{1,2}\-[0-9]{4}$/;
// use the precompiled expression above, or the following
// two lines:
//var reDateTxt = /^[0-9]{1,2}\-[0-9]{1,2}\-[0-9]{4}$/;
//var re2 = new RegExp(reDateTxt);
alert(
"result:" + re2.test("02-02-2009") +
"\nresult:" + re2.test("022-02-2009") +
"\nresult:" + re2.test("02-032-2009") +
"\nresult:" + re2.test("02-02-23009") +
"\nresult:" + re2.test(" 02-02-2009") +
"\nresult:" + re2.test("02-0a2-2009") +
"\nresult:" + re2.test("02-02-2009") +
"\nresult:" + re2.test("Random text")
);
How do you safely encode a URL using JavaScript such that it can be put into a GET string?
var myUrl = "http://example.com/index.html?param=1&anotherParam=2";
var myOtherUrl = "http://example.com/index.html?url=" + myUrl;
I assume that you need to encode the myUrl variable on that second line?
Check out the built-in function encodeURIComponent(str) and encodeURI(str).
In your case, this should work:
var myOtherUrl =
"http://example.com/index.html?url=" + encodeURIComponent(myUrl);
You have three options:
escape() will not encode: #*/+
encodeURI() will not encode: ~!##$&*()=:/,;?+'
encodeURIComponent() will not encode: ~!*()'
But in your case, if you want to pass a URL into a GET parameter of other page, you should use escape or encodeURIComponent, but not encodeURI.
See Stack Overflow question Best practice: escape, or encodeURI / encodeURIComponent for further discussion.
Stick with encodeURIComponent(). The function encodeURI() does not bother to encode many characters that have semantic importance in URLs (e.g. "#", "?", and "&"). escape() is deprecated, and does not bother to encode "+" characters, which will be interpreted as encoded spaces on the server (and, as pointed out by others here, does not properly URL-encode non-ASCII characters).
There is a nice explanation of the difference between encodeURI() and encodeURIComponent() elsewhere. If you want to encode something so that it can safely be included as a component of a URI (e.g. as a query string parameter), you want to use encodeURIComponent().
The best answer is to use encodeURIComponent on values in the query string (and nowhere else).
However, I find that many APIs want to replace " " with "+" so I've had to use the following:
const value = encodeURIComponent(value).replace('%20','+');
const url = 'http://example.com?lang=en&key=' + value
escape is implemented differently in different browsers and encodeURI doesn't encode many characters (like # and even /) -- it's made to be used on a full URI/URL without breaking it – which isn't super helpful or secure.
And as #Jochem points out below, you may want to use encodeURIComponent() on a (each) folder name, but for whatever reason these APIs don't seem to want + in folder names so plain old encodeURIComponent works great.
Example:
const escapedValue = encodeURIComponent(value).replace('%20','+');
const escapedFolder = encodeURIComponent('My Folder'); // no replace
const url = `http://example.com/${escapedFolder}/?myKey=${escapedValue}`;
I would suggest to use the qs npm package:
qs.stringify({a:"1=2", b:"Test 1"}); // gets a=1%3D2&b=Test+1
It is easier to use with a JavaScript object and it gives you the proper URL encoding for all parameters.
If you are using jQuery, I would go for the $.param method. It URL encodes an object, mapping fields to values, which is easier to read than calling an escape method on each value.
$.param({a:"1=2", b:"Test 1"}) // Gets a=1%3D2&b=Test+1
Modern solution (2021)
Since the other answers were written, the URLSearchParams API has been introduced. It can be used like this:
const queryParams = { param1: 'value1', param2: 'value2' }
const queryString = new URLSearchParams(queryParams).toString()
// 'param1=value1¶m2=value2'
It also encodes non-URL characters.
For your specific example, you would use it like this:
const myUrl = "http://example.com/index.html?param=1&anotherParam=2";
const myOtherUrl = new URL("http://example.com/index.html");
myOtherUrl.search = new URLSearchParams({url: myUrl});
console.log(myOtherUrl.toString());
This solution is also mentioned here and here.
encodeURIComponent() is the way to go.
var myOtherUrl = "http://example.com/index.html?url=" + encodeURIComponent(myUrl);
But you should keep in mind that there are small differences from PHP version urlencode() and as #CMS mentioned, it will not encode every character. Guys at http://phpjs.org/functions/urlencode/ made JavaScript equivalent to phpencode():
function urlencode(str) {
str = (str + '').toString();
// Tilde should be allowed unescaped in future versions of PHP (as reflected below), but if you want to reflect current
// PHP behavior, you would need to add ".replace(/~/g, '%7E');" to the following.
return encodeURIComponent(str)
.replace('!', '%21')
.replace('\'', '%27')
.replace('(', '%28')
.replace(')', '%29')
.replace('*', '%2A')
.replace('%20', '+');
}
I think now in 2022 to be really safe, you should always consider constructing your URLs using the URL() interface. It'll do most of the job for you. So coming to your code,
const baseURL = 'http://example.com/index.html';
const myUrl = new URL(baseURL);
myUrl.searchParams.append('param', '1');
myUrl.searchParams.append('anotherParam', '2');
const myOtherUrl = new URL(baseURL);
myOtherUrl.searchParams.append('url', myUrl.href);
console.log(myUrl.href);
// Outputs: http://example.com/index.html?param=1&anotherParam=2
console.log(myOtherUrl.href);
// Outputs: http://example.com/index.html?url=http%3A%2F%2Fexample.com%2Findex.html%3Fparam%3D1%26anotherParam%3D2
console.log(myOtherUrl.searchParams.get('url'));
// Outputs: http://example.com/index.html?param=1&anotherParam=2
Or...
const params = new URLSearchParams(myOtherUrl.search);
console.log(params.get('url'));
// Outputs: http://example.com/index.html?param=1&anotherParam=2
Something like this is assured not to fail.
To encode a URL, as has been said before, you have two functions:
encodeURI()
and
encodeURIComponent()
The reason both exist is that the first preserves the URL with the risk of leaving too many things unescaped, while the second encodes everything needed.
With the first, you could copy the newly escaped URL into address bar (for example) and it would work. However your unescaped '&'s would interfere with field delimiters, the '='s would interfere with field names and values, and the '+'s would look like spaces. But for simple data when you want to preserve the URL nature of what you are escaping, this works.
The second is everything you need to do to make sure nothing in your string interfers with a URL. It leaves various unimportant characters unescaped so that the URL remains as human readable as possible without interference. A URL encoded this way will no longer work as a URL without unescaping it.
So if you can take the time, you always want to use encodeURIComponent() -- before adding on name/value pairs encode both the name and the value using this function before adding it to the query string.
I'm having a tough time coming up with reasons to use the encodeURI() -- I'll leave that to the smarter people.
What is URL encoding:
A URL should be encoded when there are special characters located inside the URL. For example:
console.log(encodeURIComponent('?notEncoded=&+'));
We can observe in this example that all characters except the string notEncoded are encoded with % signs. URL encoding is also known as percentage encoding because it escapes all special characters with a %. Then after this % sign every special character has a unique code
Why do we need URL encoding:
Certain characters have a special value in a URL string. For example, the ? character denotes the beginning of a query string. In order to successfully locate a resource on the web, it is necessary to distinguish between when a character is meant as a part of string or part of the URL structure.
How can we achieve URL encoding in JavaScript:
JavaScript offers a bunch of built-in utility functions which we can use to easily encode URLs. These are two convenient options:
encodeURIComponent(): Takes a component of a URI as an argument and returns the encoded URI string.
encodeURI(): Takes a URI as an argument and returns the encoded URI string.
Example and caveats:
Be aware of not passing in the whole URL (including scheme, e.g., https://) into encodeURIComponent(). This can actually transform it into a not functional URL. For example:
// for a whole URI don't use encodeURIComponent it will transform
// the / characters and the URL won't fucntion properly
console.log(encodeURIComponent("http://www.random.com/specials&char.html"));
// instead use encodeURI for whole URL's
console.log(encodeURI("http://www.random.com/specials&char.html"));
We can observe f we put the whole URL in encodeURIComponent that the forward slashes (/) are also converted to special characters. This will cause the URL to not function properly anymore.
Therefore (as the name implies) use:
encodeURIComponent on a certain part of a URL which you want to encode.
encodeURI on a whole URL which you want to encode.
To prevent double encoding, it's a good idea to decode the URL before encoding (if you are dealing with user entered URLs for example, which might be already encoded).
Let’s say we have abc%20xyz 123 as input (one space is already encoded):
encodeURI("abc%20xyz 123") // Wrong: "abc%2520xyz%20123"
encodeURI(decodeURI("abc%20xyz 123")) // Correct: "abc%20xyz%20123"
A similar kind of thing I tried with normal JavaScript:
function fixedEncodeURIComponent(str){
return encodeURIComponent(str).replace(/[!'()]/g, escape).replace(/\*/g, "%2A");
}
You should not use encodeURIComponent() directly.
Take a look at RFC3986: Uniform Resource Identifier (URI): Generic Syntax
sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
/ "*" / "+" / "," / ";" / "="
The purpose of reserved characters is to provide a set of delimiting characters that are distinguishable from other data within a URI.
These reserved characters from the URI definition in RFC3986 ARE NOT escaped by encodeURIComponent().
MDN Web Docs: encodeURIComponent()
To be more stringent in adhering to RFC 3986 (which reserves !, ', (, ), and *), even though these characters have no formalized URI delimiting uses, the following can be safely used:
Use the MDN Web Docs function...
function fixedEncodeURIComponent(str) {
return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
return '%' + c.charCodeAt(0).toString(16);
});
}
Performance
Today (2020.06.12) I performed a speed test for chosen solutions on macOS v10.13.6 (High Sierra) on browsers Chrome 83.0, Safari 13.1, and Firefox 77.0. This results can be useful for massive URLs encoding.
Conclusions
encodeURI (B) seems to be fastest, but it is not recommended for URLs
escape (A) is a fast cross-browser solution
solution F recommended by MDN is medium fast
solution D is slowest
Details
For solutions
A
B
C
D
E
F
I perform two tests
for short URL - 50 characters - you can run it HERE
for long URL - 1M characters - you can run it HERE
function A(url) {
return escape(url);
}
function B(url) {
return encodeURI(url);
}
function C(url) {
return encodeURIComponent(url);
}
function D(url) {
return new URLSearchParams({url}).toString();
}
function E(url){
return encodeURIComponent(url).replace(/[!'()]/g, escape).replace(/\*/g, "%2A");
}
function F(url) {
return encodeURIComponent(url).replace(/[!'()*]/g, function(c) {
return '%' + c.charCodeAt(0).toString(16);
});
}
// ----------
// TEST
// ----------
var myUrl = "http://example.com/index.html?param=1&anotherParam=2";
[A,B,C,D,E,F]
.forEach(f=> console.log(`${f.name} ?url=${f(myUrl).replace(/^url=/,'')}`));
This snippet only presents code of chosen solutions
Example results for Chrome
Nothing worked for me. All I was seeing was the HTML of the login page, coming back to the client side with code 200. (302 at first but the same Ajax request loading login page inside another Ajax request, which was supposed to be a redirect rather than loading plain text of the login page).
In the login controller, I added this line:
Response.Headers["land"] = "login";
And in the global Ajax handler, I did this:
$(function () {
var $document = $(document);
$document.ajaxSuccess(function (e, response, request) {
var land = response.getResponseHeader('land');
var redrUrl = '/login?ReturnUrl=' + encodeURIComponent(window.location);
if(land) {
if (land.toString() === 'login') {
window.location = redrUrl;
}
}
});
});
Now I don't have any issue, and it works like a charm.
Here is a live demo of encodeURIComponent() and decodeURIComponent() JavaScript built-in functions:
<!DOCTYPE html>
<html>
<head>
<style>
textarea{
width: 30%;
height: 100px;
}
</style>
<script>
// Encode string to Base64
function encode()
{
var txt = document.getElementById("txt1").value;
var result = btoa(txt);
document.getElementById("txt2").value = result;
}
// Decode Base64 back to original string
function decode()
{
var txt = document.getElementById("txt3").value;
var result = atob(txt);
document.getElementById("txt4").value = result;
}
</script>
</head>
<body>
<div>
<textarea id="txt1">Some text to decode
</textarea>
</div>
<div>
<input type="button" id="btnencode" value="Encode" onClick="encode()"/>
</div>
<div>
<textarea id="txt2">
</textarea>
</div>
<br/>
<div>
<textarea id="txt3">U29tZSB0ZXh0IHRvIGRlY29kZQ==
</textarea>
</div>
<div>
<input type="button" id="btndecode" value="Decode" onClick="decode()"/>
</div>
<div>
<textarea id="txt4">
</textarea>
</div>
</body>
</html>
Encode URL String
var url = $(location).attr('href'); // Get the current URL
// Or
var url = 'folder/index.html?param=#23dd&noob=yes'; // Or specify one
var encodedUrl = encodeURIComponent(url);
console.log(encodedUrl);
// Outputs folder%2Findex.html%3Fparam%3D%2323dd%26noob%3Dyes
For more information, go to, jQuery Encode/Decode URL String.
Use fixedEncodeURIComponent function to strictly comply with RFC 3986:
function fixedEncodeURIComponent(str) {
return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
return '%' + c.charCodeAt(0).toString(16);
});
}
You can use ESAPI library and encode your URL using the below function. The function ensures that '/'s are not lost to encoding while the remainder of the text contents are encoded:
function encodeUrl(url)
{
String arr[] = url.split("/");
String encodedUrl = "";
for(int i = 0; i<arr.length; i++)
{
encodedUrl = encodedUrl + ESAPI.encoder().encodeForHTML(ESAPI.encoder().encodeForURL(arr[i]));
if(i<arr.length-1) encodedUrl = encodedUrl + "/";
}
return url;
}
Don't forget the /g flag to replace all encoded ' '
var myOtherUrl = "http://example.com/index.html?url=" + encodeURIComponent(myUrl).replace(/%20/g,'+');
I always use this to encode stuff for URLs. This is completely safe because it will encode every single character even if it doesn't have to be encoded.
function urlEncode(text) {
let encoded = '';
for (let char of text) {
encoded += '%' + char.charCodeAt(0).toString(16);
}
return encoded;
}
let name = `bbb`;
params = `name=${name}`;
var myOtherUrl = `http://example.com/index.html?url=${encodeURIComponent(params)}`;
console.log(myOtherUrl);
Use backtick now in ES6 to encode urls
try this - https://bbbootstrap.com/code/encode-url-javascript-26885283