0

I have a css file in which a class name appears multiple times. Call it .foo The same name also appears in the file as foo and #foo

I'm trying to create a JavaScript regular expression that can match the css class .foo but disregard the other variations foo and #foo.

So far I've tried the following variations without success:

css.replace(/.foo/g,"")

css.replace(/^.foo/g,"")

css.replace(/^.foo*/g,"")

css.replace(/\b.foo/g,"")

css.replace(/.foo\b/g,"")
4
  • . in regex means "any character". Escape it. Commented May 7, 2014 at 16:38
  • Go read the tutorial at www.regular-expressions.info. Commented May 7, 2014 at 16:39
  • I wonder what if we have some .foo word such as in an image URL in the CSS file? replacing like this is too dangerous. Commented May 7, 2014 at 16:42
  • So you should do like this css.replace(/\.foo(?=[^{]*\{)/g,"") Commented May 7, 2014 at 16:48

2 Answers 2

5

Escape a dot in your regular expression:

css.replace(/\.foo/g, '');

Otherwise it will match any non newline character before foo.

If you care about matching only .foo and not .foobar you may add \b to the regex as @Niet suggested in the comments: /\.foo\b/g.

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

6 Comments

@NiettheDarkAbsol たのむぞ。ZIG!!
+1 because you know what you doing. But consider adding \b at the end so you don't match a .foobar class.
@NiettheDarkAbsol Yeah, that makes perfect sense. Thanks.
although this may rarely happen but it depends on the actual string foo, such as we have this in the CSS file background:url(http://whatever.foo/someimage); then we know what will happen.
@KingKing Well, I personally wouldn't do parsing of CSS document especially with regular expressions. Regarding the current case it definitely depends on the context.
|
1

You need to escape the . to get a literal dot.

css.replace(/\.foo/g, "");

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.