开发者

extracting and pasting a part of string using javascript

I have people inputting 125px and 125% I want to extract just 125 from this perform some calulation on it. 125 * 2 Then 开发者_StackOverflow社区I want to add px or % as it was set before 250px and 250%


I'm guessing something like this should work:

//str is equal to your string
var num = str.substring(0,str.search(/[^0-9]/))/1;
var sub = str.substring(str.search(/[^0-9]/));
num=num*2;
var newstr = num+sub;


Emile uses parseFloat to get the number and replace to get rid of anything that isn't the unit:

function parse(prop){
    var p = parseFloat(prop),
        q = prop.replace(/^[\-\d\.]+/, '');

    ...
}

Then p is the number, and q is the unit.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜