1

Есть строка в которой несколько правил CSS. Пример:

".sleep span,body{text-align:center}body{background-color:#EBD8D0;height:100%;margin:0}"

Как убрать все селекторы и оставить только правила и их значения?

2 ответа 2

0

Попробуйте regex:

{(.+?)}

function getSelectors(source) {
  const template = /{(.+?)}/g;
  let match;
  let output = [];
  while (match = template.exec(source)) {
    output.push(match[1]);
  }

  return output;
}

var results = getSelectors(".sleep span,body{text-align:center}body{background-color:#EBD8D0;height:100%;margin:0}");
console.log(JSON.stringify(results));

3
  • ты пробовал данное регулярное выражение в яваскрипте? По крайней мере в хроме выдает: Uncaught SyntaxError: Invalid regular expression: /(?<={).+?(?=})/: Invalid group
    – Grundy
    22 мая 2017 в 18:33
  • @Grundy мы с вами пива не пили, так что давайте на вы. Исправил.
    – MihailPw
    22 мая 2017 в 19:10
  • @IvanKucher обновил ответ.
    – MihailPw
    22 мая 2017 в 19:11
0

Спасибо пользователю AGS17, за подсказку)

const regex = /{[ \n]*(.+?)[ \n]*}/gm;
const str = `html{height:100%}body{display:flex;min-height:100%;font:100 normal 16px/1.6 georgia,times,serif;background:#111}#db{display:none}canvas{display:block;margin:0 auto;align-self:flex-start}.btn{font-size:inherit;width:140px}.info-popup-container{display:inline-block;position:relative}}`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }

    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

Кому нужно вот реализация - https://jsfiddle.net/npzaygn4/2/

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.