简体   繁体   中英

How to find an exact different numbers from string using jquery or javascript

I need to find a number from a string value like:

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

I have used this method via JQuery:

JavaScript & HTML Code:

 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> 

So, the output for:
POST ID is like post-092348192357990021
BLOG ID is like blog-124938250235712450 .

But, I just need the digits for each one for example:
POST ID like this: 092348192357990021
BLOG ID like this: 124938250235712450 .

I hope you help me guys
Thanks in advance!

Use RegEx capture groups () and select the capture via it's index [1] .

If you only need numbers you could also just capture the numbers with \\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> 

If that's the exact format, you don't even need a regex.

 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); 
 <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> 

Just use split and pop after you've converted your object to a String:

 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); 
 <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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM