从js cssText字符串中搜索和删除css属性

时间:2018-05-07 20:50:25

标签: javascript css string

我正在查看元素的cssText并输入以下字符串:

输入:

"position: absolute; left: 33.999%; top: 835px; opacity: 1; transition-property: opacity, transform; transition-duration: 0.4s; transition-delay: 0ms;"

我正在寻找创建一个解析字符串并返回以下内容的函数:

输出:

"position: absolute;  left: 33.999%;  top: 835px;"

编辑:
这是我的尝试,但这样做会更有效吗?

let str = 'position: absolute; left: 33.999%; top: 835px; opacity: 1; transition-property: opacity, transform; transition-duration: 0.4s; transition-delay: 0ms;';
let keys = ['opacity', 'transition'];

function cleanStr(str, keys) {
    let splitStr = str.split(';');
    let matchingItems = [];

    for (let a = 0; a < splitStr.length; a++) {
        for (let b = 0; b < keys.length; b++) {
            if (splitStr[a].search(keys[b]) !== -1) {
                if (matchingItems.indexOf(splitStr[a]) === -1) {
                    matchingItems.push(splitStr[a]);
                }
            }
        }
    }

    return splitStr.filter((filteredStr) => {
        return matchingItems.indexOf(filteredStr) === -1;
    }).join('; ')
}

cleanStr(str, keys);

这是codepen

1 个答案:

答案 0 :(得分:0)

O(n)解决方案是构建一个反映规则的对象,删除相应的键,然后对输出进行字符串化:

const cleanStr = (str, keys) => {
  const rules = str.split(';').reduce((rules, rule) => {
    const match = rule.match(/(\w+):\s*(\w+)/);
    if (match) {
      const [_, name, value] = match;
      rules[name] = value
    }
    return rules;
  }, {});
  keys.forEach(key => delete rules[key]);
  return Object.entries(rules).reduce((str, [key, value]) => `${str} ${key}: ${value};`, "");
};

const str = 'position: absolute; left: 33.999%; top: 835px; opacity: 1; transition-property: opacity, transform; transition-duration: 0.4s; transition-delay: 0ms;';
const keys = ['opacity', 'transition'];


console.log(cleanStr(str, keys));

现在,为了安全起见,您可以使用ES2015地图,因为密钥可能是任意(不安全)输入:

const cleanStr = (str, keys) => {
  const items = str.split(';').map(rule => {
    const match = rule.match(/(\w+):\s*(\w+)/);
    return match ? [match[1], [match[2]]] : null;
  }).filter(v => !!v);
  const rules = new Map(items);
  keys.forEach(key => rules.delete(key));
  return [...rules].reduce((str, [key, value]) => `${str} ${key}: ${value};`, "");
}
const str = 'position: absolute; left: 33.999%; top: 835px; opacity: 1; transition-property: opacity, transform; transition-duration: 0.4s; transition-delay: 0ms;';
const keys = ['opacity', 'transition'];
console.log(cleanStr(str, keys));