javascript - About interception of strings
ringa_lee
ringa_lee 2017-05-19 10:11:49
0
8
634

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
ringa_lee

ringa_lee

reply all(8)
漂亮男人

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

仅有的幸福

Use regular rules

console.log('8px'.match(/(\d+)/)[0])
Peter_Zhu

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 a = '8px';
a.slice(0,-2);
大家讲道理

parseInt,parseFloat,slice,regexp

洪涛
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/; // 使用这个正则匹配
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]
}
黄舟

I’m speechless for you guys, can’t I use parseInt, parseFloat

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template