如何用jQuery或JavaScript提取字符串中的精确数字部分
Hey there! Extracting the pure numeric parts from your POST IDs (like post-092348192357990021) and BLOG IDs (like blog-124938250235712450) is totally straightforward. Let me walk you through a few reliable approaches depending on the language you're working with:
Two simple ways to get the job done here:
- Split method: Since your IDs follow a consistent
prefix-numberformat, just split the string on the hyphen and grab the last part. This preserves leading zeros perfectly:post_id = "post-092348192357990021" numeric_part = post_id.split('-')[-1] # Output: "092348192357990021" blog_id = "blog-124938250235712450" numeric_part = blog_id.split('-')[-1] # Output: "124938250235712450" - Regex method: If you want to be more explicit about matching digits (in case the format ever has extra characters), use a regex to capture all numeric characters:
import re pattern = r'\d+' numeric_part = re.search(pattern, post_id).group() # Same leading-zero-preserving result
Similar logic applies here:
- Split method: Grab the second element after splitting on the hyphen:
const postId = "post-092348192357990021"; const numericPart = postId.split('-')[1]; // Output: "092348192357990021" - Regex method: Use
match()to extract the numeric sequence:const numericPart = postId.match(/\d+/)[0]; // Works just as well, keeps leading zeros
If you need a regex that specifically targets the format prefix-numbers (to avoid accidental matches elsewhere), use this capture group pattern:
^\w+-(\d+)$
- Breakdown:
^= Start of the string\w+= Matches the prefix (likepostorblog)-= Exact hyphen separator(\d+)= Captures one or more digits (this is the part you want)$= End of the string
In languages that support capture groups, you can extract just the first captured group to get your pure numeric string, complete with leading zeros.
Any of these methods will reliably give you the numeric part you need—pick the one that fits your tech stack best!
内容的提问来源于stack exchange,提问作者Oussama Bouyardane

