cssregexatom-editorclass-names

Regex for replacing class names throughout codebase in Atom Editor


I've been struggling with this for the last few days. I apologize if this is a duplicate, I wasn't able to find what I needed when searching for this particular question.

I have class names like the following:

class="block underline primary"

className="text-center block primary-dark"

class="grey bg-black inline-block block"

I'd like to search an entire codebase using Atom's regex search feature and replace every instance with a new class name. I would need the following rules:

  1. Make sure the string is contained in class="" or className=""
  2. Make sure it's only matching the exact word, so in the above it would only match block and not inline-block if that's what I was searching for.

I currently have this which almost does what I need, but isn't accounting for className or class and will return paragraphs or things not contained within a class which I don't want:

(\s(block)\s)|(="(block)\s)|(\s(block)")

Is there any way to do a regex find and replace in one fell swoop? I understand I might not get everything because classes can be programmatically added, but I'd like to get as much as possible with find and replace and not screw other things up. Any help or direction is greatly appreciated.

edit

I also need to account for class names like the following:

class="block block-title blockDisabled"

So in the end I only want to target block and nothing else.


Solution

  • You could use the following expression:

    (className|class)="(?:block|block\s([^"]*)|([^"]*)\sblock|([^"]*)\sblock(?=\s)([^"]*))"
    

    Live Example Here

    From there, if you want to remove the block class, you would use $1="$2$3$4$5" for the replacement.

    However, if you want to replace the block class, as your title implies, then you would use $1="$2$3$4$5 replacement-class" for the replacement (where the string "replacement-class" is the class you're replacing the block class with).

    Explanation: