I am new to Javascript and recently I wanted to use regular expression in order to get a number from url and store it into a var as string and another var as digit. For example I want to get the number 55 from the below webpage (which is not an accrual page) and I want to store it in a var.
I tried this but it is not working
https://www.google.com/55.html
url.replace(/(\d+)(\.html)$/, function(str, p1, p2) {
return((Number(p1) + 1) + p2);
Please I need help but not with jQuery because it does not make a lot of sense to me.
var numPortion = url.match(/(\d+)\.html/)[1]
(Assumes a match; if it might not match, check the results before applying the array subscript.)
Try this
var a="https://www.google.com/55.html";
var match = a.match(/(\d+)(\.html)/);
match is an array,
match[0] contains the matched expression from your script,
match[1] is the number (the 1st parenthesis),
and so on
var url = 'http://www.google.com/55.html';
var yournumber = /(\d+)(\.html)$/.exec(url);
yournumber = yournumber && yournumber[1]; // <-- shortcut for using if else
Related
I have a requirement of removing a query parameter coming with a REST API call. Below are the sample URLs which need to be considered. In each of this URL, we need to remove 'key' parameter and its value.
/test/v1?key=keyval¶m1=value1¶m2=value2
/test/v1?key=keyval
/test/v1?param1=value1&key=keyval
/test/v1?param1=value1&key=keyval¶m2=value2
After removing the key parameter, the final URLs should be as follows.
/test/v1?param1=value1¶m2=value2
/test/v1?
/test/v1?param1=value1
/test/v1?param1=value1=¶m2=value2
We used below regex expression to match and replace this query string in php. (https://regex101.com/r/pK0dX3/1)
(?<=[?&;])key=.*?($|[&;])
We couldn't use the same regex in java script. Once we use it in java script it gives some syntax errors. Can you please help us to figure out the issue with the same regex ? How can we change this regex to match and remove query parameter as mentioned above?
Obviously lookbehind isn't supported in Javascript hence your regex won't work.
In Javascript you can use this:
repl = input.replace(/(\?)key=[^&]*(?:&|$)|&key=[^&]*/gmi, '$1');
RegEx Demo
Regex is working on 2 paths using regex alternation:
If this query parameter is right after ? then we grab till & after parameter and place ? back in replacement.
If this query parameter is after & then &key=value is replaced by an empty string.
The regex works in PHP but not in Javascript because Javascript does not support lookbehind.
The easiest fix here would be to replace the lookbehind (?<=[?&;]) with the equivalent characters in a capturing group ([?&;]) and use a backreference ($1) to insert this bit back into the replacement string.
For example:
var path = '/test/v1?key=keyval¶m1=value1¶m2=value2';
var regex = /([?&;])key=.*?($|[&;])/;
console.log(path.replace(regex, '$1'); // outputs '/test/v1?param1=value1¶m2=value2'
Not convinced regex would be the most reliable way of removing a query parameter, but that's a different story :-)
Just in case you want to do it without a regex, here is a function that will do the trick:
var removeQueryString = function (str) {
var qm = str.lastIndexOf('?');
var path = str.substr(0, qm + 1);
var querystr = str.substr(qm + 1);
var params = querystr.split('&');
var keyIndex = -1;
for (var i = 0; i < params.length; i++) {
if (params[i].indexOf("key=") === 0) {
keyIndex = i;
break;
}
}
if (keyIndex != -1) {
params.splice(keyIndex, 1);
}
var result = path + params.join('&');
return result;
};
The lookbehind feature isn't available in javascript, so to test the character before the key/value, you must match it. To make the pattern works whatever the position in the query part of the url, you can use an alternation in a non-capturing group, and you capture the question mark:
url = url.replace(/(?:&|(\?))key=[^&#]*(?:(?!\1).)?/, '$1');
Note: the # is excluded from the character class to prevent the fragment part (if any) of the url to be matched with key value.
I'm doing kind of a reverse templating thing, I have a string, and I know the template used to generate it, I want to get the variable value.
For example:
URL: http://c.tile.osm.org/24/7881145/7385476.png
Template: http://{s}.tile.osm.org/{z}/{x}/{y}.png
I would like to get the zoom level ({z}) from the tile's URL, in this case 24. This exact Template url will not always be used (it varies based on what basemap is used, etc.), but I'll always be looking for the {z} value.
It looks like blint may have beat me to it, but essentially what you want to do is generate a regular expression from your template and execute it:
function zFromTemplate(str, template) {
var sr = template.replace("?", "\\?")
.replace(/\{[^z]\}/g, ".*?")
.replace(/\{z\}/g, "(.+)");
var rex = new RegExp(sr),
parts = rex.exec(str);
if(parts) {
return parts[1];
}
return null;
}
And here's a codepen demonstrating it's use. If nothing else it's a little more succinct than the originally accepted answer.
You can capture values using a regex. This thread is similar to your case, and here would be your solution:
var myString = "http://c.tile.osm.org/24/7881145/7385476.png";
var myRegexp = /http:\/\/[A-z]\.tile\.osm\.org\/([0-9]+)\/([0-9]+)\/([0-9]+)\.png/;
var match = myRegexp.exec(myString);
alert(match[1]); // 24
And here's the fiddle: http://jsfiddle.net/2sx4t/
EDIT:
Following to your comment, here's the most flexible code I could quickly provide you: http://jsfiddle.net/2sx4t/4/
var myString = "http://c.tile.osm.org/24/7881145/7385476.png";
var myTemplate = "http://{s}.tile.osm.org/{z}/{y}/{x}.png";
var myString2 = "//tiles.arcgis.com/tiles/c/arcgis/rest/services/TimeZones/MapServer/tile/223774/24/2636";
var myTemplate2 = "//tiles.arcgis.com/tiles/{s}/arcgis/rest/services/TimeZones/MapServer/tile/{x}/{z}/{y}";
var z = extractToken(myTemplate, myString, '{z}');
alert(z); // 24
var z2 = extractToken(myTemplate, myString, '{z}');
alert(z2); // 24
The tricks in this code is the combination of the use of template.indexOf(m) to be able to find the order of your tokens and String.replace() to generate the appropriate RegExp.
Note that I shuffled the order of the tokens in myTemplate2and that it sill works.
Don't expect magic from RegExp, magic is in our brains ;-)
Bonus with map return, independantly of other tokens: http://jsfiddle.net/2sx4t/8/
Well, if you're sure that the {z} parameter is the only 1 or 2 digits element in your URL, you can try with regexp:
var myRegexp = /.*\/([0-9]{1,2})\/.*/;
This would match the last occurrence of any one or two digits enclosed in two slashes (/1/, /24/, ...)
I have a url in the formathttp://localhost:8080/testURL/location/#/old/Ds~1016,
The value 1016 will change based on the page selected.. is it possible in javascript to get the number 1016 part from url(based on page selected)???
Ive tried the function
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.search);
if (results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
You could also try it this way
window.location.href.split('~').pop(-1)
that should give you "1016"
Although the following would be better
window.location.href.split('/').pop(-1).split('~').pop(-1)
to make sure it is the last "/" element you are splitting
UPDATE
I always prefer using split() if it is for a single condition because the code is more understandable even though regex give better performance in the longer run. You can check the performance of regex vs split here
Try this:
regex = new RegExp("[0-9]*$");
regex.exec(window.location.hash);
To get the number, just use regex.exec(window.location.hash)[0], and then you may need to check whether it is 4 digits width.
I guess you can use the built-in window.location. And without regex you can do:
a = "http://localhost:8080/testURL/location/#/old/Ds~1016";
a.substring(a.indexOf("~")+1); // 1016
Or in a simpler way, you can use this:
window.location.hash.split('~')[1]
You can see the fiddle here: http://jsfiddle.net/DqzQF/
Feel free to try out all the URLs.
window.location.hash.split('~')[1]
Explanation:
We first grab the hash i.e. #/old/Ds~1016
by window.location.hash
Now, we split the hash with ~ (I assume that comes only one time in url)
split returns an array with Ds at 0th index and 1016 at 1st index.
So, finally
window.location.hash.split('~')[1] returns `1016`
I am trying to extract a number from a string with regular expression as I am told this would be the best approach for what I am wanting to do.
Here is the string:
http://domain.com/uploads/2011/09/1142_GF-757-S-white.jpg&h=208&w=347&zc=1&q=90&a=c&s=&f=&cc=&ct=
and I am trying to extract 208 from (height) from the string. so I know I have to look for "&h=" in the expression but I don't know what to do after that. How can I match between that and the next "&" but not include them as well...
Thanks..
Regular expression to match an h url parameter containing an integer value.
[&?]h=(\d+)
The Javascript:
var match = /[&?]h=(\d+)/.exec(url_string);
alert(match[1]);
Learn more about Regular Expressions.
To get the entire h=xxxx parameter, you can use this generic function (which you can reuse elsewhere for other purposes) and pass it the desired key:
function getParameterFromURL(url, key) {
var re = new RegExp("[&?]" + key + "=([^&]*)");
var matches = url.match(re);
if (matches) {
return(matches[1]);
}
return(null);
}
var url = "http://domain.com/uploads/2011/09/1142_GF-757-S-white.jpg&h=208&w=347&zc=1&q=90&a=c&s=&f=&cc=&ct=";
var parm = getParameterFromURL(url, "h");
See http://jsfiddle.net/jfriend00/86MEy/ for a working demo.
I have a text string that can be any number of characters that I would like to attach an order number to the end. Then I can pluck off the order number when I need to use it again. Since there's a possibility that the number is variable length, I would like to do a regular expression that catch's everything after the = sign in the string ?order_num=
So the whole string would be
"aijfoi aodsifj adofija afdoiajd?order_num=3216545"
I've tried to use the online regular expression generator but with no luck. Can someone please help me with extracting the number on the end and putting them into a variable and something to put what comes before the ?order_num=203823 into its own variable.
I'll post some attempts of my own, but I foresee failure and confusion.
var s = "aijfoi aodsifj adofija afdoiajd?order_num=3216545";
var m = s.match(/([^\?]*)\?order_num=(\d*)/);
var num = m[2], rest = m[1];
But remember that regular expressions are slow. Use indexOf and substring/slice when you can. For example:
var p = s.indexOf("?");
var num = s.substring(p + "?order_num=".length), rest = s.substring(0, p);
I see no need for regex for this:
var str="aijfoi aodsifj adofija afdoiajd?order_num=3216545";
var n=str.split("?");
n will then be an array, where index 0 is before the ? and index 1 is after.
Another example:
var str="aijfoi aodsifj adofija afdoiajd?order_num=3216545";
var n=str.split("?order_num=");
Will give you the result:
n[0] = aijfoi aodsifj adofija afdoiajd and
n[1] = 3216545
You can substring from the first instance of ? onward, and then regex to get rid of most of the complexities in the expression, and improve performance (which is probably negligible anyway and not something to worry about unless you are doing this over thousands of iterations). in addition, this will match order_num= at any point within the querystring, not necessarily just at the very end of the querystring.
var match = s.substr(s.indexOf('?')).match(/order_num=(\d+)/);
if (match) {
alert(match[1]);
}