1

I'm working with regex in order to obtain a word from a string. I have a css class which has multiple classes like: "foo foo-bar foo-bar2 baz-foo" and I want to extract the word after every "foo-" string. In this case will be an array of two elements: "bar" and "bar2".

Does anyone know any way to do it using regex or, even with a javascript function?

I tried things like: /foo-\w+/g or /foo-\w+-\w+/g but I'm not an expert of regex.

Thank you in advance,

4
  • you are meaning "after" Commented Aug 29, 2014 at 15:26
  • What are you trying to accomplish? If you're trying to pass data in the class name why not just using the data-* attributes? Commented Aug 29, 2014 at 15:27
  • foo-(\S+), grab the string inside group index 1. Commented Aug 29, 2014 at 15:28
  • Yes @AmitJoki, sorry for my english. Commented Aug 29, 2014 at 15:55

1 Answer 1

3

You are actually after the word after foo-. Use foo-(\S+) and the group 1 will contain what you want.

Sign up to request clarification or add additional context in comments.

3 Comments

it's better to use \S+
Yes it depends if OP has word characters that he only wants if not \S+ is fine for just matching the non-whitespace.
And what if I want only the word(s) after "foo-"? @AvinashRaj e.g if I have "foo-bar" and "foo-bar-baz" I want to obtain "bar" and "bar-baz". It is possible with a single regex or I have to split the result?

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.