如何检查是否有任何CSS属性与Javascript字符串?

时间:2017-09-29 03:38:02

标签: javascript jquery

检查超过1,000个句子的代码

Javascript内置了CSS index我可以查看一个句子吗?

目前......

如果我想查看CSS properties下面的句子,我必须创建一个array与......((ALL))CSS properties.然后检查每个句子对array. { {1}}




阵列

css_checker = [
"width","height","background","background color", "text decoration line", "right",
"table layout", "page break before", //and on… and… on and on………………

// I really don't want to use this array
// Using this is like a last resort
// I was hoping for a better way than this
]

输入

a = "A CSS property named animation fill mode is in this string"

b = "There are no CSS properties in this string"

c = "Width, height, and animation properties are in this string"

d = "Column rule width and transform origin are in this string"


马成顺

a:名为animation fill mode的CSS属性在此字符串

b:此字符串中没有CSS属性

c:Widthheightanimation属性在这些字符串中

d:Column rule widthtransform origin在这些字符串中


输出

a:是的

b:假

c:true

d:true

如何使用

if ( /*Sentence has CSS property*/ ) {
        //run this code
}


我想做的是

找出第一个CSS属性所在的位置......然后在该点拆分它。

实施例


输入

名为动画填充模式和宽度的CSS属性在此字符串

匹配

名为animation fill mode and width is in this string

的CSS属性

输出

动画填充模式和宽度在此字符串

2 个答案:

答案 0 :(得分:4)

您可以在此使用some来测试字符串。如果您从元素文本中抓取,只需传入element.textContent



function containsCSSProp(str) {
    css_checker = ["width","height","background","background color", "text decoration line", "right", "table layout", "page break before", "animation", "column rule width", "transform origin"];
    return css_checker.some(prop => str.toLowerCase().includes(prop));
}

console.log(containsCSSProp("A CSS property named animation fill mode is in this string"));
console.log(containsCSSProp("There are no CSS properties in this string"));
console.log(containsCSSProp("Width, height, and animation properties are in this string"));
console.log(containsCSSProp("Column rule width and transform origin are in this string"));




答案 1 :(得分:0)

let css_checker = ['width','height','background','background color', 'text decoration line', 'right','table layout', 'page break before'];
let a = 'A CSS property named animation fill mode is in this string';
let b = 'There are no CSS properties in this string';
let c = 'Width, height, and animation properties are in this string';
let d = 'Column rule width and transform origin are in this string';

for (let i = 0, max = css_checker.length; i < max; i++) {
    css_checker[i] = css_checker[i].replace(/\s/g, '');
}

function checkString(str, cssRules) {
    let string = str.replace(/\s/g, '');

    for (let i = 0, max = cssRules.length; i < max; i++) {
        if (string.toLowerCase().indexOf(cssRules[i]) !== -1) {
            console.log('true');
            return;
        }
    }

    console.log('false');
}



checkString(a, css_checker);
checkString(b, css_checker);
checkString(c, css_checker);
checkString(d, css_checker);

另一种变体! 10 000个句子需要8毫秒,它比第一个答案快