0

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

5 Answers 5

2

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(/~([^~]+?)\//);
Sign up to request clarification or add additional context in comments.

1 Comment

What is this negated match?
2

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.

4 Comments

Thanks for sharing this link regex101.com/r/xU4nZ6 I am new to this site seems like great place to go.
You are right the expression I got was different from what i had reported. Apologies I have corrected myself.
Still, this does what you want and that's all that matters :)
Yes Compadre, but in the interest of disclosure I reported this.
1

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.

Comments

1

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

1 Comment

This wrapping around will give me a capturing group. Am I right?
0

You could just do a string replace.

url.replace('~', '');
url.replace('/', '');

http://www.w3schools.com/jsref/jsref_replace.asp

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.