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 /"]
ie just childrens-day
.
Thanks
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.
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(/~([^~]+?)\//);
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('/', '');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.