Ad

Replace CSS "#" (ID) With .(Class)

- 1 answer

I've a CSS string like

    #xyz{
          color:#ee2ee2;
      }
     .abc{
        background-color:#FFFFFF;
        border-color:1px solid #eee;
     }
    .def #xyz{
       border-color:1px solid #ddd;
    }


I need to replace the #xyz (or any other ID selector) with .xyz without changing the color: #ee2ee2(or any other color selector). Basic java-script code would do

I've tried some regex but it fails a few cases

cssText.replace(/#([a-zA-Z])/gm, '.$1');
Ad

Answer

This will replace # with . only when there is a { somewhere after in the same line.

cssText = `
  #xyz
  {
     color:#ee2ee2;
  }
  .abc{
     background-color:#FFFFFF;
     border-color:1px solid #eee;
  }
  .def #xyz{
     border-color:1px solid #ddd;
  }
  body{background-color:#fff000;}.ig26{padding:20px;}.icts{width:200px;height:200px;padding:10px;} 
`;
console.log(cssText.replace(/#([a-zA-Z])(?=[^}]*{)/g, '.$1'));

Ad
source: stackoverflow.com
Ad