如何使用jquery或javascript从字符串中找到完全不同的数字

时间:2018-03-01 22:32:39

标签: javascript jquery html blogger

我需要从字符串值中找到一个数字,如:

tag:example.com,1999:blog-124938250235712450.post-092348192357990021

我通过JQuery使用了这个方法:

JavaScript& HTML代码:

var getId  = 'tag:example.com,1999:blog-124938250235712450.post-092348192357990021',
    postID = getId.match(/post-\w*/),
    blogID = getId.match(/blog-\w*/);

/* Print Post ID */
$('#post-id').html(postID);

/* Print Blog ID */
$('#blog-id').html(blogID);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Getting Post ID : <span id='post-id'></span>
<br/>
Getting Blog ID : <span id='blog-id'></span>

所以,输出为:
POST ID post-092348192357990021一样 BLOG ID blog-124938250235712450类似。

但是,我只需要每个数字,例如:
POST ID ,如下所示:092348192357990021
BLOG ID ,如下所示:124938250235712450

我希望你帮助我们 提前谢谢!

3 个答案:

答案 0 :(得分:3)

使用RegEx捕获组()并通过索引[1]选择捕获。

如果您只需要数字,您也可以使用\d来捕获数字。

var getId  = 'tag:example.com,1999:blog-124938250235712450.post-092348192357990021',
    postID = getId.match(/post-(\d*)/),
    blogID = getId.match(/blog-(\d*)/);

/* Print Post ID */
$('#post-id').html(postID[1]);

/* Print Blog ID */
$('#blog-id').html(blogID[1]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Getting Post ID : <span id='post-id'></span>
<br/>
Getting Blog ID : <span id='blog-id'></span>

答案 1 :(得分:1)

如果这是确切的格式,您甚至不需要正则表达式。

&#13;
&#13;
var getId  = 'tag:example.com,1999:blog-124938250235712450.post-092348192357990021';
var [postID, blogID] = getId.split(":blog-")[1].split(".post-");

/* Print Post ID */
$('#post-id').html(postID);

/* Print Blog ID */
$('#blog-id').html(blogID);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Getting Post ID : <span id='post-id'></span>
<br/>
Getting Blog ID : <span id='blog-id'></span>
&#13;
&#13;
&#13;

答案 2 :(得分:-1)

在将对象转换为String后,只需使用split和pop:

&#13;
&#13;
var getId  = 'tag:example.com,1999:blog-124938250235712450.post-092348192357990021',
    postID = getId.match(/post-\w*/).toString().split('-').pop(),
    blogID = getId.match(/blog-\w*/).toString().split('-').pop();


/* Print Post ID */
$('#post-id').html(postID);

/* Print Blog ID */
$('#blog-id').html(blogID);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Getting Post ID : <span id='post-id'></span>
<br/>
Getting Blog ID : <span id='blog-id'></span>
&#13;
&#13;
&#13;