javascript 如何获取字符串的第一个单词并将其转换为 int?jQuery
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9039454/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to grab first word of string and convert it to int? jQuery
提问by BBee
I need to grab first word in string and I need to convert it to integer. How to do this using jQuery?
我需要获取字符串中的第一个单词,并且需要将其转换为整数。如何使用 jQuery 做到这一点?
example: "223 Lorem Ipsum Dolor"
示例:“223 Lorem Ipsum Dolor”
I need "223" and it must be converted into integer...
我需要“ 223”,它必须转换为整数......
Any help would be appreciated.
任何帮助,将不胜感激。
回答by Adam Rackis
You can split a string based on any character (like a space), then pass the first index to parseInt
您可以根据任何字符(如空格)拆分字符串,然后将第一个索引传递给 parseInt
var str = "223 lorem";
var num = parseInt(str.split(' ')[0], 10);
Note that parseInt
takes a second parameter, which is the radix. If you leave that off, and try to parse a number with a leading zero, like 09
, it'll assume you're in base 8, and will return 0, since 09
isn't a valid base-8 value.
请注意,parseInt
它采用第二个参数,即基数。如果你不这样做,并尝试解析一个带有前导零的数字,比如09
,它会假设你在 base 8 中,并且将返回 0,因为09
它不是一个有效的 base-8 值。
Or, as John points out, using the unary +
operator is a nifty way to convert a string to a number:
或者,正如 John 指出的那样,使用一元运算+
符是将字符串转换为数字的好方法:
var str = "223 lorem";
var num = +str.split(' ')[0];
回答by ShankarSangoli
Try this.
试试这个。
var str = "223 Lorem Ipsum Dolor";
str = $.trim(str).split(" ");
var num = parseInt(str[0], 10);
回答by Lucian Vasile
I think it's better to use something like:
我认为最好使用以下内容:
var str = "223 Lorem Ipsum Dolor";
var matches = str.match(/(\d+)/);
result = parseInt(matches[0]);
Maybe you'll want to wse some nots before the \d+
也许你会想要在 \d+ 之前 wse 一些 nots
回答by Surender Lohia
Try this...
试试这个...
function getFirstNumber(str) {
var matched = str.match(/^\d+/);
if(matched) {
return +matched[0]; // Get matched number (as string) and type cast to Number.
}
console.error("first word is not a number: '" + str + "'.");
return -1;
};
var str = "223 lorem";
getFirstNumber(str);