Replace %20 by a space in a 'url.split' in javascript - javascript

I know that this question has been asked more than once here. But the issue I'm facing is a bit different that the one's I checked in previous questions.
I'm retrieving the Category in a variable from the URL in my JS by doing this-
$scope.category = url.split("=")[1]
This would be a sample URL-
sitename/pagename.aspx?Category=Cars
I'm facing an issue when there is a space in the category. Say if the URL is like this-
sitename/pagename.aspx?Category=Super%20Cars
Can you please lemme know how to replace the %20 by a space along with the url.split.
Sure this isnt a right one-
$scope.category = decodeURIComponent(url.split("=")[1]);
Lemme know if you need more info guys. :)

You can try this:
url.split('%20').join(' ');

You can do it by below syntax:
var url = window.location.href;
var tempUrl = url.replace(/%20/g," ");
$scope.category = tempUrl.split("=")[1]

You need to use decodeURI to achieve this.
http://www.w3schools.com/jsref/jsref_decodeuri.asp

Use decodeURI global function available in javascript. http://www.w3schools.com/jsref/jsref_decodeuri.asp
var url="http://www.dummyserver.com/index.php?param1=hello%20world";
var queryParams=url.substring(url.indexOf("?") + 1).split("&");
for(i=0;i<queryParams.length;i++){
var splitParam = queryParams[i].split("=");
alert("Param: " + splitParam[0] + " :: Value:" + decodeURI(splitParam[1]));
}

You can convert the url into string first and then replace %20 with the space and then split,it should work,can try like this:
var str = 'sitename/pagename.aspx?Category=Super%20Cars';
var res = str.toString();
res = res.replace('%20',' ');
category = decodeURIComponent(res.split("=")[1]);

Related

Unable to replace characters in javascript

I have following url as a string:
var fb= "https://www.facebook.com/XYZ"
I want to remove https://www.facebook.com and display only /XYZ.
I tried alert(fb.replace("facebook.com","")); alert(fb.substring('facebook.com'.length));
but it didn`t help
Tried code :
alert(fb.replace("facebook.com",""));
alert(fb.substring('facebook.com'.length));
Any help will be appreciated.
Looks like you are trying to get the last part of the given url.
This will do.
alert(fb.substr(fb.lastIndexOf('/')));
Demo
This is simple. Try the following:
var fb="https://www.facebook.com/XYZ";
var x = fb.substr(fb.lastIndexOf("/"), fb.length);
Now x has got the final result in x as
"/XYZ"
Try this.
var fb = https://www.facebook.com/XYZ
fb = fb .substr(fb.indexOf("/") + 1); // Contains XYZ //
Use String#replace and a regular expression (which allows you to add flexibility in the kind of URLs you accept, like http / https or www.facebook.com / facebook.com).
var fb = 'https://www.facebook.com/XYZ'
console.log(
fb.replace(/^https?:\/\/(?:www.)?facebook.com(?=\/)/, '') //=> '/XYZ'
)
<script type="text/javascript">
var fb="https://www.facebook.com/XYZ"
fb.split('/')[3];
alert(fb.split('/')[3])
</script>
it working please try
var fb="https://www.facebook.com/XYZ";
var res = fb.replace("https://www.facebook.com", "");

Remove hash from current page’s URL

I want to remove the hash, as well as anything after it, from a URL. For example, I might have:
http://example.com/#question_1
… which slides to question no. 1 to show an error message. When the user’s input then passes validation, I need to remove #question_1 from the current location.
I’ve tried all of these, but none of them has worked for me:
document.location.href.replace(location.hash, "");
window.location.hash.split('#')[0];
window.location.hash.substr(0, window.location.hash.indexOf('#'));
Note: I don’t just want to get the URL – I want to remove it from my address bar.
history.pushState("", document.title, window.location.href.replace(/\#(.+)/, '').replace(/http(s?)\:\/\/([^\/]+)/, '') )
Try this :use .split() to split string by # and then read first element in array using index 0
var url = 'http://example.com#question_1';
var urlWithoutHash = url.split('#')[0];
alert(urlWithoutHash );
Use split in javascript
var str = "http://example.com#question_1";
alert(str.split("#")[0]);
Try this way:
var currentPath = window.location.pathname;
var myUrl = currentPath.split("#")[0];
OR
var currentPath = window.location.href;
var myUrl = currentPath.split("#")[0];
Hope it helps.
This will clear the id selector from the uri
location.hash = '';
Use .split as shown :
var str = "http://example.com#question_1";
alert((str.split("#")[0]);
or use .substring() as shown :
var str = "http://example.com#question_1";
alert((str.substring(0,str.indexOf('#'))));

Regex javascript + replace

I got few lines like these:
/coc59409.p?id=1218405784092
/acme-made-skinny-lray-orange/5616664.p?id=1218679205878
/incase-campus-brk-gray-pink-berry/7209107.p?id=1218833962192&skuId=7209107
and I need to delete in all of them what come after this ".p?id="
how can I do that?
results :
/coc59409.p?id=
/acme-made-skinny-lray-orange/5616664.p?id=
/incase-campus-brk-gray-pink-berry/7209107.p?id=
=> "/coc59409.p?id=1218405784092".replace(/\?.*$/,"")
>> "/coc59409.p"
You don't need a regular expression here - contextually what you are referring to is the query string of the URL and there are already tools in the DOM with the facility to tokenise this, for example:
var url = '/coc59409.p?id=1218405784092',
a = document.createElement('a');
a.href = url;
console.log( a.pathname ); // '/coc59409.p'
Details about the HTMLAnchorElement can be found here.
You could just split it,
var url = '/acme-made-skinny-lray-orange/5616664.p?id=1218679205878'
var urlArr = url.split('=');
console.log(urlArr[0]+'=');
Hope that helps :)
Take each line and replace id=[THE REST OF THE LINE] with id=.
Like so:
"coc59409.p?id=1218405784092".replace(/id=(.*)$/, 'id=')

Validating url with http:www as optional using regex

I am trying to validate a url where the "http:www" is optional, so the yahoo.com and http://www.yahoo.com needs to be valid url but using the following regex does not take utl3 to be valid one .
How can I fix this ??
function checkUrlTest(url){
var urlregex = new RegExp("^(https?:\/\/www\.)?(^(https?:\/\/www\.)[0-9A-Za-z]+\.+[a-z]{2,5})");
return urlregex.test(url);
}
url3 = "yahoo.com";
url4 = "www.yahoo.com";
alert(checkUrlTest(url3));
(http://)?(www\.)?[A-Za-z0-9]+\.[a-z]{2,3}
In this regex, http://www.yahoo.com, http://yahoo.com and www.yahoo.com are all valid URLs
Just check it out. All problems will resolve.
var rgx = /^\s*(http\:\/\/)?([a-z\d\-]{1,63}\.)*[a-z\d\-]{1,255}\.[a-z]{2,6}\s*$/;
Working Demo http://jsfiddle.net/fy66p/
Solution reside here: Negative Lookahead: http://www.regular-expressions.info/lookaround.html#lookahead with the www case and you should get what you are looking for. Lemme know how it goes!
Hope it fits your needs :)
code
function checkUrlTest(url){
// Try this
var urlregex = new RegExp("^(?!www | www\.)[A-Za-z0-9_-]+\.+[A-Za-z0-9.\/%&=\?_:;-]+$")
return urlregex.test(url);
}
url3 = "yahoo.com";
url4 = "www.yahoo.com";
alert('===> ' + checkUrlTest(url4) + '===> ' + checkUrlTest(url3));
function validateUrl(value)
{
var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/
return regexp.test(value);
}
if not try this:
(?i)\b((?:(?:[a-z][\w-]+:)?(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))

Remove last element from url

I need to remove the last part of the url from a span..
I have
<span st_url="http://localhost:8888/careers/php-web-developer-2"
st_title="PHP Web Developer 2" class="st_facebook_large" displaytext="facebook"
st_processed="yes"></span></span>
And I need to take the st_url and remove the php-web-developer-2 from it so it is just http://localhost:8888/careers/.
But I am not sure how to do that. php-web-developer-2 will not always be that but it won't have any / in it. It will always be a - separated string.
Any Help!!??
as simple as this:
var to = url.lastIndexOf('/');
to = to == -1 ? url.length : to + 1;
url = url.substring(0, to);
Here is a slightly simpler way:
url = url.slice(0, url.lastIndexOf('/'));
$('span').attr('st_url', function(i, url) {
var str = url.substr(url.lastIndexOf('/') + 1) + '$';
return url.replace( new RegExp(str), '' );
});
DEMO
Use this.
$('span').attr('st_url', function(i, url) {
var to = url.lastIndexOf('/') +1;
x = url.substring(0,to);
alert(x);
})​
You can see Demo
You could use a regular expression to parse the 'last piece of the url':
var url="http://localhost:8888/careers/php-web-developer";
var baseurl=url.replace(new RegExp("(.*/)[^/]+$"),"$1");
The RegExp thing basically says: "match anything, then a slash and then all non-slashes till the end of the string".
The replace function takes that matching part, and replaces it with the "anything, then a slash" part of the string.
RegexBuddy has a great deal of information on all this.
You can see it work here: http://jsfiddle.net/xKxLR/
var url = "http://localhost:8888/careers/php-web-developer-2";
var regex = new RegExp('/[^/]*$');
console.log(url.replace(regex, '/'));
First you need to parse the tag. Next try to extract st_url value which is your url. Then use a loop from the last character of the extracted url and omit them until you see a '/'. This is how you should extract what you want. Keep this in mind and try to write the code .

Categories

Resources