jQuery / 从字符串中获取数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9282935/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:35:30  来源:igfitidea点击:

jQuery / Get numbers from a string

jquery

提问by TheCarver

I have a button on my page with a class of comment_likeand an ID like comment_like_123456but the numbers at the end are variable; could be 1 to 1000000.

我的页面上有一个按钮,类comment_like和 ID 类似,comment_like_123456但最后的数字是可变的;可以是 1 到 1000000。

When this button is clicked, I need to grab the end number so I can run tasks on other elements with the same suffix.

单击此按钮时,我需要获取结束编号,以便我可以在具有相同后缀的其他元素上运行任务。

Is there an easy way of grabbing this number in jQuery?

有没有一种简单的方法可以在 jQuery 中获取这个数字?

$('.comment_like').click(function() {
    var element_id = $(this).attr('id');

    // grab number from element ID

    // do stuff with that number

});

回答by Sarfraz

You can get it like this:

你可以这样得到它:

var suffix = 'comment_like_123456'.match(/\d+/); // 123456

With respect to button:

关于按钮:

$('.comment_like').click(function(){
  var suffix = this.id.match(/\d+/); // 123456
});

回答by paislee

In your click handler:

在您的点击处理程序中:

var number = $(this).attr('id').split('_').pop();

回答by ANJYR - KODEXPRESSION

You can try this. it will extract all number from any type of string.

你可以试试这个。它将从任何类型的字符串中提取所有数字。

var suffix = 'comment_like_6846511';
alert(suffix.replace(/[^0-9]/g,''));

DEMO

演示

回答by Cory Danielson

http://jsfiddle.net/hj2nJ/

http://jsfiddle.net/hj2nJ/

var x = 'comment_like_6846511';
var y = '';

for (i = 0; i < x.length; i++)
{
    if ("" + parseInt(x[i]) != "NaN") //if the character is a number
        y = y + x[i];
}

document.write(y);

回答by meagar

This is a task for plain-old regular expressions, it has nothing to do with jQuery:

这是普通正则表达式的任务,它与 jQuery 无关:

"comment_like_123456".match(/\d+/)

=> ["123456"]

回答by Diodeus - James MacFarlane

jQuery is not a magic bullet. Use Javascript!

jQuery 不是灵丹妙药。使用Javascript!

var temp = "comment_like_123456".split("_")
alert(temp[2])

回答by mgibsonbr

Just get the id and run it through a regex.

只需获取 id 并通过正则表达式运行它。

$(mybutton).click(function() {
    var num = parseInt(/^.*\_(\d+)$/.exec(this.id)[1])
});