3

I have to match, of style contains, for example, color. This is string:

<a href="#" style="margin:50px;color:2;">test</a>

And my regex:

/(color:(.);)/

It works now, what I need to do, so it will also match color: 2;?

4
  • Why are you trying to deconstruct style strings like this? Anyway, the answer is you need to find the magic regexp character which will match a space, and--imagine this--it's a space! If you want the space to be optional, you follow it with a ?, which is a feature documented on the first page of any regexp introduction you'll find on the web. That first page will also talk about another operator, the asterisk, which matches zero or more of something, so ` *` is zero or more spaces, which is probably what you're looking for. Commented Nov 20, 2014 at 13:25
  • I want to remove each style, except of color, font-size... and some more. I am newbie in regex, so I start asking by the simple one. Commented Nov 20, 2014 at 13:27
  • To manipulate styles, manipulate the styles directly, as in element.style.fontSize = '';. CSS is a language, and it's never a good idea to try to parse or rewrite anything but the simplest language with regexps. They will break, and be hard to maintain. If you want to experiment with regexps, start with some sample problems which are more suited to regexps. Commented Nov 20, 2014 at 13:32
  • I cannot, I have issue, that TinyMCE has styles on the elements. When you copy styled text from TinyMCE, it will flag that and insert as HTML, when it is from another website, or word, whatever, it will paste as plain text. I have compelted that, but when I have selected item, copied it, pasted it in editor, there are all styles (from reset, another CSS etc...) si I have to remove each style, that is not directly added via TinyMCE. Commented Nov 20, 2014 at 13:35

1 Answer 1

3

Use \s* to match optional space characters:

/(color:\s*(.);)/

(.) will match only a single character color. If you want to match another colors with more characters, use following regular expression:

/(color:\s*([^\s;]+)\s*;)/

(used \S to match non-space character)

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

8 Comments

Thanks for fast response! This is what I was looking for.
What about color : 2? What about background-color: 2? What about 'color: 2 ;'? Also, your regexp only matches colors of a single character.
@torazaburo, Thank you for pointing that out. I updated the answer accordingly.
Also thanks for update, I wanted to ask about that. But that not work, when color is not at the end.
@debute, You can use negated character class to exclude ;: /(color:\s*([^\s;]+)\s*;)/
|

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.