Extracting number ID from a URL in Javascript - javascript

Similar to my previous question:
spliting a string in Javascript
The URLs have now changed and the unique number ID is no longer at the end of the URL like so:
/MarketUpdate/Pricing/9352730/Report
How would i extract the number from this now i cannot use the previous solution?

You could search for
/(\d+)/
and use backreference no. 1 which will contain the number. Note that this requires the number to always be delimited by slashes on both sides. If you also want to match numbers at the end of the string, use
/(\d+)(?:/|$)
In JavaScript:
var myregexp = /\/(\d+)\//;
// var my_other_regexp = /\/(\d+)(?:\/|$)/;
var match = myregexp.exec(subject);
if (match != null) {
result = match[1];
} else {
result = "";
}

If the URLs always look like that, why not use split() ?
var ID = url.split('/')[3];

urlstring = "/MarketUpdate/Pricing/9352730/Report"
$str = urlstring.split("/");
alert($str[3]);
This splits the string each time it finds the / symbol and stores it into an array, You can then get each word in the array by using $str[0]

Related

Extract strings between occurences of a specific character

I'm attempting to extract strings between occurences of a specific character in a larger string.
For example:
The initial string is:
var str = "http://www.google.com?hello?kitty?test";
I want to be able to store all of the substrings between the question marks as their own variables, such as "hello", "kitty" and "test".
How would I target substrings between different indexes of a specific character using either JavaScript or Regular Expressions?
You could split on ? and use slice passing 1 as the parameter value.
That would give you an array with your values. If you want to create separate variables you could for example get the value by its index var1 = parts[0]
var str = "http://www.google.com?hello?kitty?test";
var parts = str.split('?').slice(1);
console.log(parts);
var var1 = parts[0],
var2 = parts[1],
var3 = parts[2];
console.log(var1);
console.log(var2);
console.log(var3);
Quick note: that URL would be invalid. A question mark ? denotes the beginning of a query string and key/value pairs are generally provided in the form key=value and delimited with an ampersand &.
That being said, if this isn't a problem then why not split on the question mark to obtain an array of values?
var split_values = str.split('?');
//result: [ 'http://www.google.com', 'hello', 'kitty', 'test' ]
Then you could simply grab the individual values from the array, skipping the first element.
I believe this will do it:
var components = "http://www.google.com?hello?kitty?test".split("?");
components.slice(1-components.length) // Returns: [ "hello", "kitty", "test" ]
using Regular Expressions
var reg = /\?([^\?]+)/g;
var s = "http://www.google.com?hello?kitty?test";
var results = null;
while( results = reg.exec(s) ){
console.log(results[1]);
}
The general case is to use RegExp:
var regex1 = new RegExp(/\?.*?(?=\?|$)/,'g'); regex1.lastIndex=0;
str.match(regex1)
Note that this will also get you the leading ? in each clause (no look-behind regexp in Javascript).
Alternatively you can use the sticky flag and run it in a loop:
var regex1 = new RegExp(/.*?\?(.*?)(?=\?|$)/,'y'); regex1.lastIndex=0;
while(str.match(regex1)) {...}
You can take the substring starting from the first question mark, then split by question mark
const str = "http://www.google.com?hello?kitty?test";
const matches = str.substring(str.indexOf('?') + 1).split(/\?/g);
console.log(matches);

regex: get string in url login/test

I have a url
https://test.com/login/param2
how do I get the the second parameter "param2" from the url using REGEX?
the url can also be
https://test.com/login/param2/
So the regex should work for both urls.
I tried
var loc = window.location.href;
var locParts = loc.split('/');
and then looping through locParts, but that seems inefficient.
The "param2" can be have number, alphatical character from a-z, and a dash.
Use String#match method with regex /[^\/]+(?=\/?$)/.
var a = 'https://test.com/login/facebook',
b = 'https://test.com/login/facebook/';
var reg = /[^\/]+(?=\/?$)/;
console.log(
a.match(reg)[0],
b.match(reg)[0]
)
Or using String#split get last non-empty element.
var a = 'https://test.com/login/facebook',
b = 'https://test.com/login/facebook/';
var splita = a.split('/'),
splitb = b.split('/');
console.log(
splita.pop() || splita.pop(),
splitb.pop() || splitb.pop()
)
If you don't mind using JS only (so no regex), you can use this :
var lastParameter = window.location.href.split('/').slice(-1);
Basicaly, like you, I fetch the URL, split by the / character, but then I use the splice function to get teh last element of the split result array.
Regular expressions might be compact, but they're certainly not automatically efficient if you can do what you want without.
Here's how you can change your code:
var loc = 'https://test.com/login/facebook/'; // window.location.href;
var locParts = loc.split('/').filter(function(str) {return !!str});
var faceBookText = locParts.pop();
console.log(faceBookText);
The filter removes the last empty item you would get if the url ends with '/'. That's all you need, then just take the last item.

regex: any string between two slashes first of them is prefixed with a defined string

I'd like to get the talker name of some mp3s files paths such as the following:
/assets/audio/James_Lee/001.mp3
/assets/audio/Marc_Smith/001.mp3
/aasets/audio/blahblah/001.mp3
In the previous example we note that each talker name is surrounded by two slashes where the first of them is prefixed with the word audio. I need a pattern that matches names like the example above using javascript.
I tried at http://regexpal.com/ :
audio/.*/
but it only matches *audio/The_name/* where I need *The_name* only. The other thing I don't know how could I use such patterns with javascript replace().
This will get your the name: (?<=\/assets\/audio\/).*(?=\/)
Here's the regex in use: http://regexr.com?34747
Considering Javascript, you could do this:
var string = "/assets/audio/James_Lee/001.mp3";
var name = string.replace(/^.*\/audio\/|\/[\d]+\..*$/g, '');
Try this:
var str = "/assets/audio/James_Lee/001.mp3\n/assets/audio/Marc_Smith/001.mp3";
var pattern = /audio\/(.+?)\//g;
var match;
var matches = [];
while ((match = pattern.exec(str)) !== null){
matches.push(match[1]);
}
console.log(matches);
// If you want a string with only the names, you can re-combine the matches
str = matches.join('\n');
how about this?
str.replace(/.*audio\/([^\/]*)\/.*/,"$1")

Javascript substring() trickery

I have a URL that looks like http://mysite.com/#id/Blah-blah-blah, it's used for Ajax-ey bits. I want to use substring() or substr() to get the id part. ID could be any combination of any length of letters and numbers.
So far I have got:
var hash = window.location.hash;
alert(hash.substring(1)); // remove #
Which removes the front hash, but I'm not a JS coder and I'm struggling a bit. How can I remove all of it except the id part? I don't want anything after and including the final slash either (/Blah-blah-blah).
Thanks!
Jack
Now, this is a case where regular expressions will make sense. Using substring here won't work because of the variable lengths of the strings.
This code will assume that the id part wont contain any slashes.
var hash = "#asdfasdfid/Blah-blah-blah";
hash.match(/#(.+?)\//)[1]; // asdfasdfid
The . will match any character and
together with the + one or more characters
the ? makes the match non-greedy so that it will stop at the first occurence of a / in the string
If the id part can contain additional slashes and the final slash is the separator this regex will do your bidding
var hash = "#asdf/a/sdfid/Blah-blah-blah";
hash.match(/#(.+?)\/[^\/]*$/)[1]; // asdf/a/sdfid
Just for fun here are versions not using regular expressions.
No slashes in id-part:
var hash = "#asdfasdfid/Blah-blah-blah",
idpart = hash.substr(1, hash.indexOf("/"));
With slashes in id-part (last slash is separator):
var hash = "#asdf/a/sdfid/Blah-blah-blah",
lastSlash = hash.split("").reverse().indexOf("/") - 1, // Finding the last slash
idPart = hash.substring(1, lastSlash);
var hash = window.location.hash;
var matches = hash.match(/#(.+?)\//);
if (matches.length > 1) {
alert(matches[1]);
}
perhaps a regex
window.location.hash.match(/[^#\/]+/)
Use IndexOf to determine the position of the / after id and then use string.substr(start,length) to get the id value.
var hash = window.location.hash;
var posSlash = hash.indexOf("/", 1);
var id = hash.substr(1, posSlash -1)
You need ton include some validation code to check for absence of /
This one is not a good aproach, but you wish to use if you want...
var relUrl = "http://mysite.com/#id/Blah-blah-blah";
var urlParts = [];
urlParts = relUrl.split("/"); // array is 0 indexed, so
var idpart = = urlParts[3] // your id will be in 4th element
id = idpart.substring(1) //we are skipping # and read the rest
The most foolproof way to do it is probably the following:
function getId() {
var m = document.location.href.match(/\/#([^\/&]+)/);
return m && m[1];
}
This code does not assume anything about what comes after the id (if at all). The id it will catch is anything except for forward slashes and ampersands.
If you want it to catch only letters and numbers you can change it to the following:
function getId() {
var m = document.location.href.match(/\/#([a-z0-9]+)/i);
return m && m[1];
}

Regular expression to extract text between two sets of characters (Javascript)

I would like to extract some text between two points in a string, in Javascript
Say the string is
"start-extractThis-234"
The numbers at the end can be any number, but the hyphens are always present.
Ideally I think capturing between the two hypens should be ok.
I would like the result of the regex to be
extractThis
string = "start-extractThis-234"
console.log( string.match( '-(.*)-' )[1] );
//returns extractThis
why not just do
var toExtract = "start-extractThis-234";
var extracted = null;
var split = toExtract.split("-");
if(split.length === 3){
extracted = split[1];
}
^.+?-(.+?)-\d+$

Categories

Resources