6

I have a question for a Javascript regex ninja: How could I simplify my variable creation from a string using regex grouping? I currently have it working without using any grouping, but I would love to see a better way!

The string is:

var url = 'resources/css/main.css?detect=#information{width:300px;}';

The code that works is:

var styleStr = /[^=]+$/.exec(url).toString();
var id = /[^\#][^\{]+/.exec(styleStr).toString();
var property = /[^\{]+/.exec(/[^\#\w][^\:]+/.exec(styleStr)).toString();
var value = /[^\:]+/.exec(/[^\#\w\{][^\:]+[^\;\}]/.exec(styleStr)).toString();

This gives:

alert(id)       //information
alert(property) //width
alert(value)    //300px

Any takers?

1
  • In fact, the grammar of CSS selectors is a little more complex. (See w3.org/TR/CSS2/grammar.html) Commented May 18, 2010 at 15:59

2 Answers 2

7

Sure..

var url = 'resources/css/main.css?detect=#information{width:300px;}';
var matches = url.match(/#([^{]+){([^:]+):([^;]+)/);
var id = matches[1];
var property = matches[2];
var value = matches[3];
Sign up to request clarification or add additional context in comments.

1 Comment

I think the RegEx for multiple match should be like /RegEx/g, otherwise it will return only first match. So in above answer, it should have been var matches = url.match(/#([^{]+){([^:]+):([^;]+)/g);
1
#(?<type>.+){(?<property>.*?):(?<value>.*?);

Group "type":   information     31      11
Group "property":   width       43       5
Group "value":  300px

[Jay loves regexbuddy]

JS:

result = subject.match(/#([\s\S]+)\{([\s\S]*?):([\s\S]*?);/ig);

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.