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?
漂亮男人2017-05-19 10:13:49
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
天蓬老师2017-05-19 10:13:49
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,'' )
PHP中文网2017-05-19 10:13:49
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
巴扎黑2017-05-19 10:13:49
It is most convenient to use regular expressions
var reg = /([\d\.]+)px/; // 使用这个正则匹配
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]); // 结果arr[i].match(reg)[1]
}