I have a link like this:
http://nl.wikipedia.org/wiki/Alexandra_Stan&sa=U&ei=UULHUIIdzPnhBOKMgPgJ&ved=0CCIQFjAA&usg=AFQjCNGyCikDkoZMnnuqGo6vjMQ6b5lZkw
I would like to get rid of everything starting at '&' So this will give me a clean url:
http://nl.wikipedia.org/wiki/Alexandra_Stan
I know how to replace href like this:
$('a').each(function() {
$(this).attr("href", function(index, old) {
return old.replace("something", "something else");
});
});
But I can't figure out how to get rid of everything starting at a certain character.
You can use substr() and indexOf() to get a specific portion of the URL, from the beginning of the URL string up until the point the first ampersand is encountered.
var href = $(this).attr('href');
var url = href.substr(0, href.indexOf('&'));
Use String.prototype.split instead. It splits a string by character into an array. The most important part is that if that character is missing (in your case, '&'), it will put the entire string in the first array index anyway.
// String.prototype.indexOf:
var href = 'http://www.noAmpersandHere.com/',
url = href.substr(0, href.indexOf('&')); // ''
// String.prototype.split:
var href = 'http://www.noAmpersandHere.com/',
url = href.split('&'); // ['http://www.noAmpersandHere.com/']
url = url[0]; // 'http://www.noAmpersandHere.com/'
First: consider that the parameters list starts with ? and not with &
The anchor element you are handling already have the entire url parsed and correctly divided.
You need only to access to the correct anchor property:
https://developer.mozilla.org/en-US/docs/DOM/HTMLAnchorElement
Related
So I currently pass two variables into the url for use on another page. I get the last variable (ie #12345) with location.hash. Then from the other part of the url (john%20jacob%202) all I need is the '2'. I've got it working but feel there must be a cleaner and succinct way to handle this. The (john%20jacob%202) will change all the time to have different string lengths.
url: http://localhost/index.html?john%20jacob%202?#12345
<script>
var hashUrl = location.hash.replace("?","");
// function here to use this data
var fullUrl = window.location.href;
var urlSplit = fullUrl.split('?');
var justName = urlSplit[1];
var nameSplit = justName.split('%20');
var justNumber = nameSplit[2];
// function here to use this data
</script>
A really quick one-liner could be something like:
let url = 'http://localhost/index.html?john%20jacob%202?#12345';
url.split('?')[1].split('').pop();
// returns '2'
How about something like
decodeURI(window.location.search).replace(/\D/g, '')
Since your window.location.search is URI encoded we start by decoding it. Then replace everything that is not a number with nothing. For your particular URL it will return 2
Edit for clarity:
Your example location http://localhost/index.html?john%20jacob%202?#12345 consists of several parts, but the interesting one here is the part after the ? and before the #.
In Javascript this interesting part, the query string (or search), is available through window.location.search. For your specific location window.location.search will return ?john%20jacob%202?.
The %20 is a URI encoded space. To decode (ie. remove) all the URI encodings I first run the search string through the decodeURI function. Then I replace everything that is not a number in that string with an empty string using a regular expression.
The regular expression /\D/ matches any character that is not a number, and the g is a modifier specifying that I want to match everything (not just stop after the first match), resulting in 2.
If you know you are always after a tag, you could replace everything up until the "#"
url.replace(/^.+#/, '');
Alternatively, this regex will match the last numbers in your URL:
url.match(/(?<=\D)\d+$/);
//(positive look behind for any non-digit) one more digits until the end of the string
I want to know way to replace substring in url with new string.
https://pbs.twimg.com/media/DW7hPt9VAAAdKE7?format=jpg&name=small
after "&name=" they are many kind of size like
900x900,medium,360x360,small
let href = document.location.href;
if(!href.includes('&name=orig')){
if(href.includes(/900x900|medium|360x360|small/){ //if href have some size in regular expression
// I try to make it search for substring in regular expression
document.location.href = href.replace(/900x900|medium|360x360|small/,'orig');
}
else{ //if url don't have '&name=' like above
var adding = '&name=orig';
document.location.href = link+adding;
}
}
It not working
I don't want to write code to check all case like
if(href.includes('900x900')
if(href.includes('medium')
if(href.includes('360x360')
if(href.includes('small')
they are way to find match at once?
change if(href.includes(/900x900|medium|360x360|small/){ to
if(href.search(/900x900|medium|360x360|small/) !== -1){
as includes accepts the string not the regex.
$('.icon-displayer').css('background-image');
console.log(a)
gives me value as url("http://localhost:8080/myApp/icons/xing-square.png")
from this string i want extract only the file name i.e xing-suare.png how do i do it?
I tried
var url= $('.icon-displayer').css('background-image');
var filename = url.split('/').pop()
did not work
Javascript pop method remove the last element from an array. Use split and then get the last position of the array.
var url= $('.balaIconPicker-icon-displayer').css('background-image');
var array = url.split('/');
var filename = array[array.length - 1];
If there are no parameters, then Lucas's answer is okay and it's the one you should use. However if the string at the end is something like "test.php?id=125" you will get the "?id=125" too which may not be what you want. A regular expression can save you from this:
var url = "http://www.test.com/directory/test.php?id=128",
cleanRegexp = /\/([^\.\/]+\.[a-z]{0,3})[^\/]*$/;
var result = cleanRegexp.exec(url);
window.alert(result[1]);
the regular expression finds the last slash, then looks after it for anything that isn't a slash or a dot, then grabs the dot and the extension, finishing before any special characters.
Here is the Fiddle
I am making a web app that has multiple 'pages' but it will all be loaded client side. Seems how it is all technically on the same page, I will be using parameters after # to track the current page state while preventing postbacks. My problem is that I cant seem to select all the parameters with a regex line. The regex for split works when I use a testing tool online but does not work when I use it on my web page.
//Test data for url
//https://test.ca?hi&hey=3&test=oh+hi+mark#edit&e=1
var split = /([^&#=]+)=?([^&#]*)/g;
var url = window.location.href;
var match = split.exec(url);
//this outputs match with a length of three
//[0] = 'https://test.ca?hi'
//[1] = 'https://test.ca?hi'
//[2] = ''
I thought this should be a solved problem but I cant seem to find an answer. Which I guess leads to another question. Am I going about this the completely wrong way?
You are using the regex wrong. You just print the whole match, while you need to access the captured groups while iterating through all the matches inside 1 string.
Here is an example snippet:
var re = /([^&#=]+)=?([^&#]*)/g;
var str = 'https://test.ca?hi&hey=3&test=oh+hi+mark#edit&e=1';
var match;
while ((match = re.exec(str)) !== null) {
document.write(match[1] + "<br/>" + match[2] + "<br/><br/>");
}
Note that the first match is the "main" part of the URL. Subsequent matches are param-value pairs.
Try using window.location.hash instead. It will return the hash value (in your example url it would be #edit&e=1) and you can use string operations to do whatever you need to with that.
I have the following URL:
http://example.com/product/1/something/another-thing
Although it can also be:
http://test.example.com/product/1/something/another-thing
or
http://completelydifferentdomain.tdl/product/1/something/another-thing
And I want to get the number 1 (id) from the URL using Javascript.
The only thing that would always be the same is /product. But I have some other pages where there is also /product in the url just not at the start of the path.
What would the regex look like?
Use window.location.pathname to
retrieve the current path (excluding
TLD).
Use the JavaScript string
match method.
Use the regex /^\/product\/(\d+)/ to find a path which starts with /product/, then one or more digits (add i right at the end to support case insensitivity).
Come up with something like this:
var res = window.location.pathname.match(/^\/product\/(\d+)/);
if (res.length == 2) {
// use res[1] to get the id.
}
/\/product\/(\d+)/ and obtain $1.
Just, as an alternative, to do this without Regex (though i admit regex is awfully nice here)
var url = "http://test.example.com//mypage/1/test/test//test";
var newurl = url.replace("http://","").split("/");
for(i=0;i<newurl.length;i++) {
if(newurl[i] == "") {
newurl.splice(i,1); //this for loop takes care of situatiosn where there may be a // or /// instead of a /
}
}
alert(newurl[2]); //returns 1
I would like to suggest another option.
.match(/\/(\d+)+[\/]?/g)
This would return all matches of id's present.
Example:
var url = 'http://localhost:4000/#/trees/8/detail/3';
// with slashes
var ids = url.match(/\/(\d+)+[\/]?/g);
console.log(ids);
//without slashes
ids = url.match(/\/(\d+)+[\/]?/g).map(id => id.replace(/\//g, ''));
console.log(ids);
This way, your URL doesn't even matter, it justs retrieves all parts that are number only.
To just get the first result you could remove the g modifier:
.match(/\/(\d+)+[\/]?/)
var url = 'http://localhost:4000/#/trees/8';
var id = url.match(/\/(\d+)+[\/]?/);
//With and without slashes
console.log(id);
The id without slashes would be in the second element because this is the first group found in the full match.
Hope this helps people.
Cheers!