jquery - 使用 jQuery 获取字符串的一部分

标签 jquery string substring

HTML 代码:

<div id="block-id-45"></div>

如何使用 jQuery 获取字符串的编号 "45"

最佳答案

返回 id 末尾的数字属性使用

$(this).attr("id").match(/[\d]+$/);

以上将返回 45如果$(this)<div id="block-id-45"></div>

jsFiddle example

上面的工作方式是使用 .attr() 检索元素的 id ,然后你看id并使用 .match() 恢复其末尾的数字。 /[\d]+$/是一个正则表达式。 [\d]表示一位数字 +表示一个或多个(数字)。和$表示行尾。

<小时/>

您可以使用此函数检索 id 以 block-id- 开头的所有 div 末尾的数字。通过使用 attribute starts with selector [name^=value] .each() :

实际用法:

$(function() {

      // Select all DIS that start with 'block-id-'
      //   and iterate over each of them.
    $("div[id^='block-id-']").each(function() {

          // You could push this data to an array instead.
          // This will display it.
        $("body").append( "Id number: " + 
                            // This is the number at the end
                          $(this).attr("id").match(/[\d]+$/) +
                          "<br/>" );
    });
});​

<强> jsFiddle example

关于jquery - 使用 jQuery 获取字符串的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3722360/

相关文章:

c++ - 给定一个字符串,每当你看到单词 "ant"时,将单词 "termite"替换为字符串

javascript - 具有多个叠加层和图像按钮的 Flowplayer

javascript - 使用下拉选择对 list.js 中的项目进行排序

jquery - 如何从文本输入框中删除空格

php - 将分数转换为 html 实体

php - 为什么 PHP strlen() 返回负长度?

java - 在 Java 中拆分 * 上的字符串?

javascript - Javascript 子串是虚拟的吗?

javascript - JavaScript 中的日期不相等

Swift:从字符串中提取子字符串