typescript/javascript 解析css属性值中的长度单位
常用单位的字典树
说明:
child: 子节点
exist: 从根节点到当前节点组成的字符串是否是一个符合要求的单位
例: 如下json对象表示字符串vb是一个符合要求的单位
b节点的exist属性为false表示字符串b不是一个符合要求的单位
在child属性下v的exist值为true表示字符串vb不是一个符合要求的单位
注意: 解析时是从被解析的字符串末尾向前解析的,因为单位是在最后的
完整的字典树在文章末尾
child: {
'b': {
exist: false,
child: {
'v': {
exist: true,
child: {
}
}
}
}
主要代码
参数说明:
- object:
unitMap: 保存着用于解析str的字典树(见文章末尾 - string:
str: 待解析的字符串 - 可选参数
- boolean:
caseSensitive: 是否大小写敏感(默认为false)
- boolean:
- 返回值是一个json对象
{unit: 单位, number: 数值}
typescript
checkUnit(unitMap: any, str: string, caseSensitive?: boolean): {
unit: string,
number: number
} {
if (!unitMap || !str) { return; }
if (!caseSensitive) { str = str.toLocaleLowerCase(); }
let i: number, isMatch = false;
for (i = str.length - 1; i >= 0; i--) {
const ascii = str.charCodeAt(i);
if (ascii >= 48 && ascii <= 57) {
isMatch = unitMap.exist;
break;
} else {
if (!unitMap.child[str[i]]) { break; }
unitMap = unitMap.child[str[i]];
}
}
return isMatch ? {
unit: str.substr(i + 1),
number: Number.parseInt(str.substr(0, i + 1), 10)
} : null;
}
javascript
javascript只是把ts的变量类型去掉了
checkUnit(unitMap, str, caseSensitive?) {
if (!unitMap || !str) { return; }
if (!caseSensitive) { str = str.toLocaleLowerCase(); }
let i, isMatch;
for (i = str.length - 1; i >= 0; i--) {
const ascii = str.charCodeAt(i);
if (ascii >= 48 && ascii <= 57) {
isMatch = unitMap.exist;
break;
} else {
if (!unitMap.child[str[i]]) { break; }
unitMap = unitMap.child[str[i]];
}
}
return isMatch ? {
unit: str.substr(i + 1),
number: Number.parseInt(str.substr(0, i + 1), 10)
} : null;
}```
```js
unitMap = {
exist: false,
child: {
'b': {
exist: false,
child: {
'v': {
exist: true,
child: {
}
}
}
},
'c': {
exist: false,
child: {
'i': {
exist: true,
child: {
}
},
'p': {
exist: true,
child: {
}
}
}
},
'h': {
exist: false,
child: {
'c': {
exist: true,
child: {
}
},
'l': {
exist: true,
child: {
'r': {
exist: true,
child: {
}
}
}
},
'v': {
exist: true,
child: {
}
}
}
},
'i': {
exist: false,
child: {
'v': {
exist: true,
child: {
}
}
}
},
'm': {
exist: false,
child: {
'e': {
exist: true,
child: {
'r': {
exist: true,
child: {
}
}
}
},
'm': {
exist: true,
child: {
}
},
'c': {
exist: true,
child: {
}
}
}
},
'n': {
exist: false,
child: {
'i': {
exist: true,
child: {
'm': {
exist: false,
child: {
'v': {
exist: true,
child: {
}
}
}
}
}
}
}
},
'p': {
exist: false,
child: {
'a': {
exist: false,
child: {
'c': {
exist: true,
child: {
}
},
}
},
}
},
'q': {
exist: true,
child: {
}
},
't': {
exist: false,
child: {
'p': {
exist: true,
child: {
}
}
}
},
'w': {
exist: false,
child: {
'v': {
exist: true,
child: {
}
}
}
},
'x': {
exist: false,
child: {
'a': {
exist: false,
child: {
'm': {
exist: false,
child: {
'v': {
exist: true,
child: {
}
}
}
}
}
},
'e': {
exist: true,
child: {
}
},
'p': {
exist: true,
child: {
}
}
}
}
}
};

本文介绍如何在typescript和javascript中解析CSS属性值中的长度单位。通过建立常用单位的字典树,从字符串末尾向前解析,确保单位的正确性。文章提供了详细的解析代码示例,并附带了一个完整的字典树。
3894

被折叠的 条评论
为什么被折叠?



