RegEx - Get All Characters After Last Slash in URL - javascript

I'm working with a Google API that returns IDs in the below format, which I've saved as a string. How can I write a Regular Expression in javascript to trim the string to only the characters after the last slash in the URL.
var id = 'http://www.google.com/m8/feeds/contacts/myemail%40gmail.com/base/nabb80191e23b7d9'

Don't write a regex! This is trivial to do with string functions instead:
var final = id.substr(id.lastIndexOf('/') + 1);
It's even easier if you know that the final part will always be 16 characters:
var final = id.substr(-16);

A slightly different regex approach:
var afterSlashChars = id.match(/\/([^\/]+)\/?$/)[1];
Breaking down this regex:
\/ match a slash
( start of a captured group within the match
[^\/] match a non-slash character
+ match one of more of the non-slash characters
) end of the captured group
\/? allow one optional / at the end of the string
$ match to the end of the string
The [1] then retrieves the first captured group within the match
Working snippet:
var id = 'http://www.google.com/m8/feeds/contacts/myemail%40gmail.com/base/nabb80191e23b7d9';
var afterSlashChars = id.match(/\/([^\/]+)\/?$/)[1];
// display result
document.write(afterSlashChars);

Just in case someone else comes across this thread and is looking for a simple JS solution:
id.split('/').pop(-1)

this is easy to understand (?!.*/).+
let me explain:
first, lets match everything that has a slash at the end, ok?
that's the part we don't want
.*/ matches everything until the last slash
then, we make a "Negative lookahead" (?!) to say "I don't want this, discard it"
(?!.*) this is "Negative lookahead"
Now we can happily take whatever is next to what we don't want with this
.+
YOU MAY NEED TO ESCAPE THE / SO IT BECOMES:
(?!.*\/).+

this regexp: [^\/]+$ - works like a champ:
var id = ".../base/nabb80191e23b7d9"
result = id.match(/[^\/]+$/)[0];
// results -> "nabb80191e23b7d9"

This should work:
last = id.match(/\/([^/]*)$/)[1];
//=> nabb80191e23b7d9

Don't know JS, using others examples (and a guess) -
id = id.match(/[^\/]*$/); // [0] optional ?

Why not use replace?
"http://google.com/aaa".replace(/(.*\/)*/,"")
yields "aaa"

Related

Regex to get the text between two characters?

I want to replace a text after a forward slash and before a end parantheses excluding the characters.
My text:
<h3>notThisText/IWantToReplaceThis)<h3>
$('h3').text($('h3').text().replace(regEx, 'textReplaced'));
Wanted result after replace:
notThisText/textReplaced)
I have tried
regex = /([^\/]+$)+/ //replaces the parantheses as well
regex = \/([^\)]+) //replaces the slash as well
but as you can see in my comments neither of these excludes both the slash and the end parantheses. Can someone help?
A pattern like /(?<=\/)[^)]+(?=\))/ won't work in JS as its regex engine does not support a lookbehind construct. So, you should use one of the following solutions:
s.replace(/(\/)[^)]+(\))/, '$1textReplaced$2')
s.replace(/(\/)[^)]+(?=\))/, '$1textReplaced')
s.replace(/(\/)[^)]+/, '$1textReplaced')
s.replace(/\/[^)]+\)/, '/textReplaced)')
The (...) forms a capturing group that can be referenced to with $ + number, a backreference, from the replacement pattern. The first solution is consuming / and ), and puts them into capturing groups. If you need to match consecutive, overlapping matches, use the second solution (s.replace(/(\/)[^)]+(?=\))/, '$1textReplaced')). If the ) is not required at the end, the third solution (replace(/(\/)[^)]+/, '$1textReplaced')) will do. The last solution (s.replace(/\/[^)]+\)/, '/textReplaced)')) will work if the / and ) are static values known beforehand.
You can use str.split('/')
var text = 'notThisText/IWantToReplaceThis';
var splited = text.split('/');
splited[1] = 'yourDesireText';
var output = splited.join('/');
console.log(output);
Try Following: In your case startChar='/', endChar = ')', origString=$('h3').text()
function customReplace(startChar, endChar, origString, replaceWith){
var strArray = origString.split(startChar);
return strArray[0] + startChar + replaceWith + endChar;
}
First of all, you didn't define clearly what is the format of the text which you want to replace and the non-replacement part. For example,
Does notThisText contain any slash /?
Does IWantToReplaceThis contain any parentheses )?
Since there are too many uncertainties, the answer here only shows up the pattern exactly matches your example:
yourText.replace(/(\/).*?(\))/g, '$1textReplaced$2')
var text = "notThisText/IWantToReplaceThis";
text = text.replace(/\/.*/, "/whatever");
output : "notThisText/whatever"`

How to extract a particular text from url in JavaScript

I have a url like http://www.somedotcom.com/all/~childrens-day/pr?sid=all.
I want to extract childrens-day. How to get that? Right now I am doing it like this
url = "http://www.somedotcom.com/all/~childrens-day/pr?sid=all"
url.match('~.+\/');
But what I am getting is ["~childrens-day/"].
Is there a (definitely there would be) short and sweet way to get the above text without ["~ and /"] i.e just childrens-day.
Thanks
You could use a negated character class and a capture group ( ) and refer to capture group #1. The caret (^) inside of a character class [ ] is considered the negation operator.
var url = "http://www.somedotcom.com/all/~childrens-day/pr?sid=all";
var result = url.match(/~([^~]+)\//);
console.log(result[1]); // "childrens-day"
See Working demo
Note: If you have many url's inside of a string you may want to add the ? quantifier for a non greedy match.
var result = url.match(/~([^~]+?)\//);
Like so:
var url = "http://www.somedotcom.com/all/~childrens-day/pr?sid=all"
var matches = url.match(/~(.+?)\//);
console.log(matches[1]);
Working example: http://regex101.com/r/xU4nZ6
Note that your regular expression wasn't actually properly delimited either, not sure how you got the result you did.
Use non-capturing groups with a captured group then access the [1] element of the matches array:
(?:~)(.+)(?:/)
Keep in mind that you will need to escape your / if using it also as your RegEx delimiter.
Yes, it is.
url = "http://www.somedotcom.com/all/~childrens-day/pr?sid=all";
url.match('~(.+)\/')[1];
Just wrap what you need into parenteses group. No more modifications into your code is needed.
References: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
You could just do a string replace.
url.replace('~', '');
url.replace('/', '');
http://www.w3schools.com/jsref/jsref_replace.asp

Matching the last digit or digits after a forward slash

In a JavaScript function in my Rails app, I'm trying to get the id of a recipe. Looking inside the event object like this
e.delegateTarget.baseURI
produces the uri, the last number of which (after the forward slash) is the id I want.
http://myroute.com/users/2/recipes/6
Of course, that id could be much longer in the future, so I need to be able to get all the digits after the last forward slash.
I tried to get the last id this way
var uri = e.delegateTarget.baseURI
var re = /^(.*[\\\/\d])/;
var recipe_id = uri.match(re);
The matched slash is supposed to be the last one because .* matches greedily, and then I look for any digit. This is all wrong. I'm not very experienced with regular expressions. Can you help?
A very simple way to do this would be to use string.split()
var uri = "http://myroute.com/users/2/recipes/6",
splituri = uri.split('/');
recipe_id = splituri[splituri.length - 1] // access the last index
Edit:
Even easier with the .pop() method, which returns the popped value
like elclanrs said.
var uri = e.delegateTarget.baseURI,
recipe_id = uri.split('/').pop();
You should use the special character $, which means end of input:
re = /\d+$/; //matches one or more digits from the end of the input
Here is a good resource on JavaScript regular expressions.

How can I get the last part of a songkick URL using regex?

I need to get the last part after the slash from this URL or even just the number using regex:
http://www.songkick.com/artists/2884896-netsky
Does anyone know how I can go about doing this?
Many thanks,
Joe
I've got a regex pattern to find everything after the last slash - it is ([^//]+)$ . Thanks!
don't know if this is ok for you:
last part:
"http://www.songkick.com/artists/2884896-netsky".replace(/.*\//,"")
"2884896-netsky"
number:
"http://www.songkick.com/artists/2884896-netsky".replace(/.*\//,"").match(/\d+/)
["2884896"]
Try this:
var s = "http://www.songkick.com/artists/2884896-netsky";
s.match(/[^\/]+$/)[0]
[^\/]+ matches one or more characters other than /
$ matches the end of the string
For just the number, try:
var value = s.match(/(\d+)[^\/\d]+$/)[1];
value = parseInt(value, 10); // convert it to an Integer
(\d+) matches any Number and groups it
[^\/\d]+ matches anything besides Numbers or /
More Info on Javascript Regular Expressions

Javascript Regex: Match Up to Or Between But Not Including

For instance, I am using a simple regex to match everything before the first space:
var str = '14:00:00 GMT';
str.match(/(.*?)\s/)[0]; //Returns '14:00:00 ' note the space at the end
To avoid this I can do this:
str.match(/(.*?)\s/)[0].replace(' ', '');
But is there a better way? Can I just not include the space in the regex? Another examle is finding something between 2 characters. Say I want to find the 00 in the middle of the above string.
str.match(/:(.*?):/)[0]; //Returns :00: but I want 00
str.match(/:(.*?):/)[0].replace(':', ''); //Fixes it, but again...is there a better way?
I think you just need to change the index from 0 to 1 like this:
str.match(/(.*?)\s/)[1]
0 means the whole matched string, and 1 means the first group, which is exactly what you want.
#codaddict give another solution.
str.match(/(.*?)(?=\s)/)[0]
(?=\s) means lookahead but not consume whitespace, so the whole matched string is '14:00:00' but without whitespace.
You can use positive lookahead assertions as:
(.*?)(?=\s)
which says match everything which is before a whitespace but don't match the whitespace itself.
Yes there is, you can use character classes:
var str = '14:00:00 GMT';
str.match(/[^\s]*/)[0]; //matches everything except whitespace
Your code is quite close to the answer, you just need to replace [0] with [1].
When str.match(/:(.*?):/) is executed, it returns an object, in this example, the object length is 2, it looks like this:
[":00:","00"]
In index 0, it stores the whole string that matches your expression, in index 1 and later, it stores the result that matches the expression in each brackets.
Let's see another example:
var str = ":123abcABC:";
var result = str.match(/:(\d{3})([a-z]{3})([A-Z]{3}):/);
console.log(result[0]);
console.log(result[1]);
console.log(result[2]);
console.log(result[3]);
And the result:
:123abcABC:
123
abc
ABC
Hope it's helpful.
Try this,
.*(?=(\sGMT))
RegexBuddy ScreenShot

Categories