How to replace / except in http:// - javascript

I have a string and I need to replace %2f with /, except in http://.
Example:
var str = "http://locahost%2f";
str = str.replace(/%2f/g, "/");
Somehow I got str to output http:/locahost/.
Thanks in advance!

What should be used
You should use decodeURIComponent or decodeURI functions to decode encoded strings like yours. For example, decodeURIComponent("http://locahost%2f") will return http://localhost/.
That being said, decodeURIComponent should be used to decode components of a URI and not a full URI like http://locahost/.
You should look at this answer, it explains what is the difference between decodeURIComponent and decodeURI and when each should be used.
A workaround
As the first / are not encoded, it makes it difficult to find a Javascript functions doing exactly what you want. A working solution to decode your %2f after http:// would be to use String.prototype.split.
Working example:
var encoded = "http://localhost%2f";
var encodedArray = str.split("://");
var decoded = encodedArray[0] + "://" + encodedArray[1].replace(/%2f/g, "/");

This should work:
str = str.replace("%2f", "/");

Related

How to convert string from ENV to hex in JavaScript? [duplicate]

I have a string in JS in this format:
http\x3a\x2f\x2fwww.url.com
How can I get the decoded string out of this? I tried unescape(), string.decode but it doesn't decode this. If I display that encoded string in the browser it looks fine (http://www.url.com), but I want to manipulate this string before displaying it.
Thanks.
You could write your own replacement method:
String.prototype.decodeEscapeSequence = function() {
return this.replace(/\\x([0-9A-Fa-f]{2})/g, function() {
return String.fromCharCode(parseInt(arguments[1], 16));
});
};
"http\\x3a\\x2f\\x2fwww.example.com".decodeEscapeSequence()
There is nothing to decode here. \xNN is an escape character in JavaScript that denotes the character with code NN. An escape character is simply a way of specifying a string - when it is parsed, it is already "decoded", which is why it displays fine in the browser.
When you do:
var str = 'http\x3a\x2f\x2fwww.url.com';
it is internally stored as http://www.url.com. You can manipulate this directly.
If you already have:
var encodedString = "http\x3a\x2f\x2fwww.url.com";
Then decoding the string manually is unnecessary. The JavaScript interpreter would already be decoding the escape sequences for you, and in fact double-unescaping can cause your script to not work properly with some strings. If, in contrast, you have:
var encodedString = "http\\x3a\\x2f\\x2fwww.url.com";
Those backslashes would be considered escaped (therefore the hex escape sequences remain unencoded), so keep reading.
Easiest way in that case is to use the eval function, which runs its argument as JavaScript code and returns the result:
var decodedString = eval('"' + encodedString + '"');
This works because \x3a is a valid JavaScript string escape code. However, don't do it this way if the string does not come from your server; if so, you would be creating a new security weakness because eval can be used to execute arbitrary JavaScript code.
A better (but less concise) approach would be to use JavaScript's string replace method to create valid JSON, then use the browser's JSON parser to decode the resulting string:
var decodedString = JSON.parse('"' + encodedString.replace(/([^\\]|^)\\x/g, '$1\\u00') + '"');
// or using jQuery
var decodedString = $.parseJSON('"' + encodedString.replace(/([^\\]|^)\\x/g, '$1\\u00') + '"');
You don't need to decode it. You can manipulate it safely as it is:
var str = "http\x3a\x2f\x2fwww.url.com";
​alert(str.charAt(4)); // :
alert("\x3a" === ":"); // true
alert(str.slice(0,7))​; // http://
maybe this helps: http://cass-hacks.com/articles/code/js_url_encode_decode/
function URLDecode (encodedString) {
var output = encodedString;
var binVal, thisString;
var myregexp = /(%[^%]{2})/;
while ((match = myregexp.exec(output)) != null
&& match.length > 1
&& match[1] != '') {
binVal = parseInt(match[1].substr(1),16);
thisString = String.fromCharCode(binVal);
output = output.replace(match[1], thisString);
}
return output;
}
2019
You can use decodeURI or decodeURIComponent and not unescape.
console.log(
decodeURI('http\x3a\x2f\x2fwww.url.com')
)

Javascript replacing /, str.replace not working

I'm having a really stupid issue where javascript is replacing every '/' with '%2F' in a url. Here is what i have now:
var url;
url = $(this).val();
url = str.replace('%2F', '/');
window.location.href = $(this).val();
What have I done wrong here?
You need to decode the url to convert the special characters back to what they should be (like changing %2F back to /). To do this, you can use decodeURI:
url = $(this).val();
url = decodeURI(url);
However, sometimes spaces get replaced by + instead of %20. So, to handle these cases, you must replace all + with %20 before decoding your url.
url = $(this).val();
url = url.replace('+', '%20');
url = decodeURI(url);
And now url is the decoded version of the url.

Escape Base64 String in URL?

For some reason I need to put a Base64 encoded string in the URL, i.e.
<script>
var URL = "localhost:8080/MyApp/order?z=AAAAAAAEJs4"
</script>
The URL is generated by Java, problem here is I can only use java to make the Base 64 encoded string to be URL friendly, but not javascript friendly, so fire bug give me the following error:
SyntaxError: unterminated string literal
Apparently there are charactors in the Base64 string requires escaping. However I cannot use escape() or URLencoding() method as the request will directly deliver to the controller and manipulated by java code, so there is no "next page" in this situation.
So how to make this work then?
If your're trying to convert that z url attribute into an understandable string/variable, you have to use a library to convert that. Below is a link to a base64 library for Javascript that you must load in.
http://www.webtoolkit.info/javascript-base64.html
You maybe also need a library to access the z attribute in your url. I would recommend this:
https://github.com/allmarkedup/purl
Just in case it helps, here is a short JS code requiring no dependency:
String.prototype.base64EncodeUrl = function () {
var str = this;
str = window.btoa(unescape(encodeURIComponent( str )));
return str.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=+$/, '');
};
String.prototype.base64DecodeUrl = function () {
var str = this, str_pad = (str + '===');
str = str_pad.slice(0, str.length + (str.length % 4));
str = str.replace(/-/g, '+').replace(/_/g, '/');
return decodeURIComponent(escape(window.atob( str )));
};

Javascript replace url with string

I have a string of url encoded characters.
wondering if there is a javascript function that can replace all the url encoded characters with normal string characters.
i know i can use the replace function, but it only replaces one certain character an not all at once
for example, I am looking for one function that will replace all the url encoded characters in this string:
string urlEncoded = '1%20day%20%40work!%20Where%20are%20you%3F'
and give me this string:
string replaced = '1 day # work! Where are you?'
thanks a lot
Use decodeURIComponent(string) for that purpose.
string urlEncoded = '1%20day%20%40work!%20Where%20are%20you%3F';
string replaced = decodeURIComponent(urlEncoded);
alert(replaced);
More info here: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/decodeURIComponent
string replaced = decodeURIComponent(urlEncoded);
There is also just decodeURI but this does not cope with "special" characters, such as & ? ! # etc
Use decodeURIComponent(urlEncoded)
You are looking for unescape
var decoded = unescape(urlEncoded);

Simple Regex question

I want to remove this from a url string
http://.....?page=1
I know this doesn't work, but I was wondering how you would do this properly.
document.URL.replace("?page=[0-9]", "")
Thanks
It seems like you want to get rid of the protocol and the querystring. So how about just concatenating the remaining parts?
var loc = window.location;
var str = loc.host + loc.pathname + loc.hash;
http://jsfiddle.net/9Ng3Z/
I'm not entirely certain what the requirements are, but this fairly simple regex works.
loc.replace(/https?\:\/\/([^?]+)(\?|$)/,'$1');
It may be a naive implementation, but give it a try and see if it fits your need.
http://jsfiddle.net/9Ng3Z/1/
? is a regex special character. You need to escape it for a literal ?. Also use regular expression literals.
document.URL.replace(/\?page=[0-9]/, "")
The answer from #patrick dw is most practical but if you're really curious about a regular expression solution then here is what I would do:
var trimUrl = function(s) {
var r=/^http:\/\/(.*?)\?page=\d+.*$/, m=(""+s).match(r);
return (m) ? m[1] : s;
}
trimUrl('http://foo.com/?page=123'); // => "foo.com/"
trimUrl('http://foo.com:8080/bar/?page=123'); // => "foo.com:8080/bar/"
trimUrl('foobar'); // => "foobar"
You're super close. To grab the URL use location.href and make sure to escape the question mark.
var URL = location.href.replace("\?page=[0-9]", "");
location.href = URL; // and redirect if that's what you intend to do
You can also strip all query string parameters:
var URL = location.href.replace("\?.*", "");

Categories

Resources