开发者

using a regular expression on a variable?

Say I have this for example:

$(function() {

    var seconds = 142.097019375;

    seconds = seconds.replace(/\.[0-9]*/, '');

    alert(seconds); 

});

This wont work, but if seconds was $('.seco开发者_开发百科nds').html(); it would replace it, is there anyway to perform a regex on a jquery variable as such.


If your variable is a number and you're really trying to extract just the integer part, then you'll want to use Math.floor or Math.ceil:

var int_part = seconds > 0 ? Math.floor(seconds) : Math.ceil(seconds);


You can't call String methods (specifically, replace) on Numbers. Try converting the Number to a String first:

seconds = (seconds + "").replace(/\.[0-9]*/, '');


If you are merely trying to drop the decimals from a number, this is not a good use of regular expressions.

Use parseInt(), like:

parseInt(seconds, 10);

See that it does the same thing - http://jsfiddle.net/bzAGe/


It's not working because the Number object doesn't have a .replace function.

Use seconds = seconds.toString().replace(/\.[0-9]*/, '');


Force it to a string first:

$(function() {

    var seconds = "" + 142.097019375;

    seconds = seconds.replace(/\.[0-9]*/, '');

    alert(seconds); 

});


You want to get the integer part of this var? Use Math.floor. There are other method that you might want to know, look a Math object reference.

Definition and Usage

The floor() method rounds a number DOWNWARDS to the nearest integer, and returns the result.

Syntax

Math.floor(x)

Parameter     Description
x             Required. A number

Using regex

replace is a String method, you can convert it to a string before performing the replace

(seconds.toString()).replace()

or declare seconds as a string

var seconds = "value";

Javascript String object

  • replace() Searches for a match between a substring (or regular expression) and a string, and replaces the matched substring with a new substring

Syntax

string.replace(regexp/substr,newstring)

Parameter         Description
regexp/substr     Required. A substring or a regular expression.
newstring         Required. The string to replace the found value in parameter 1
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜