如何抓住字符串的第一个字,并将其转换为int? jQuery的 [英] How to grab first word of string and convert it to int? jQuery

查看:137
本文介绍了如何抓住字符串的第一个字,并将其转换为int? jQuery的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要抓取字符串中的第一个单词,并且需要将其转换为整数。
如何使用jQuery做到这一点?



示例:223 Lorem Ipsum Dolor

我需要 223 ,并且必须将其转换为整数 ...

任何帮助将不胜感激。

解决方案

您可以根据任何字符(如空格)拆分字符串,然后传递第一个index to parseInt

  var str =223 lorem; 
var num = parseInt(str.split('')[0],10);

DEMO



请注意, parseInt 需要第二个参数,这是基数。如果你不这样做,并试图用一个前导零来解析一个数字,比如 09 ,它会假定你的基数为8,并且返回0,因为 09 不是有效的基数8值。




或者,正如John指出的那样,使用一元 + 运算符是将字符串转换为数字的一种很好的方式:

  var str =223 lorem; 
var num = + str.split('')[0];

DEMO


I need to grab first word in string and I need to convert it to integer. How to do this using jQuery?

example : "223 Lorem Ipsum Dolor"

I need "223" and it must be converted into integer...

Any help would be appreciated.

解决方案

You can split a string based on any character (like a space), then pass the first index to parseInt

var str = "223 lorem";
var num = parseInt(str.split(' ')[0], 10);

DEMO

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.


Or, as John points out, using the unary + operator is a nifty way to convert a string to a number:

var str = "223 lorem";
var num = +str.split(' ')[0];

DEMO

这篇关于如何抓住字符串的第一个字,并将其转换为int? jQuery的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆