For example, there is a string a = "8px";
The number of digits in the number is not necessarily certain. If I want to intercept the number, I want to use a.substring(0,a.indexOf("p")). I originally wanted to use a.substring(0,-2); But after checking, I found out that the substring parameter cannot be a negative number, but I think a.substring(0,a.indexOf("p")) is a bit troublesome. Is there a more direct optimization method?
ringa_lee
var a="88px";
If the format is the same, the first parts are numbers and only the numbers need to be extracted, you can use:
parseInt(a);//88
The first one can use the substring method: a.substring(0,a.length-2)
The second one can use regular expressions: var a='8px';a.replace(/px$/ig,'' )
var str1 = "8px",
str2 = "88px",
str3 = "888px",
str4 = "8.88px";
str1.replace(/(.*)px/, "$1"); //8
str2.replace(/(.*)px/, "$1"); //88
str3.replace(/(.*)px/, "$1"); //888
str4.replace(/(.*)px/, "$1"); //8.88
It is most convenient to use regular expressions
var reg = /([\d\.]+)px/; // 使用這個(gè)正則匹配
var arr = ['8px', '18px', '28px', '0.08px']
for (let i = 0, len = arr.length; i < len; i++) {
console.log(arr[i], arr[i].match(reg)[1]); // 結(jié)果arr[i].match(reg)[1]
}