请求协助:用JavaScript正则表达式移除字符串中的_数字x数字片段
JavaScript Solution to Remove "_[Number]x[Number]" from Strings
Hey there! No worries at all—regular expressions can feel super overwhelming when you're just starting out, so let's walk through this clearly for your exact use case.
The Core Solution
Here's the straightforward JavaScript code to take your example string and strip out that _300x300-style segment:
// Your original string (works with any numbers in place of 300) const originalStr = "blablabla_300x300.jpg"; // Replace the target pattern with an empty string const cleanedStr = originalStr.replace(/_\d+x\d+/, ""); console.log(cleanedStr); // Output: "blablabla.jpg"
Breaking Down the Regular Expression
Let's unpack what /_\d+x\d+/ actually does, piece by piece:
_: Matches the literal underscore character (no special escaping needed here)\d+:\dstands for any digit (0-9), and the+means "one or more of the preceding character"—so this matches any sequence of numbers (like 300, 5, 1234, etc.)x: Matches the literal letter "x" exactly as it appears- Putting it all together:
_\d+x\d+targets any substring that starts with an underscore, followed by one or more digits, an x, then another set of one or more digits. Perfect for your_300x300pattern!
Handling Multiple Matches
If your string might have more than one of these _NumberxNumber segments (like "photo_100x200_400x400.png"), just add the g (global) flag to the regex to replace all occurrences:
const originalStr = "photo_100x200_400x400.png"; const cleanedStr = originalStr.replace(/_\d+x\d+/g, ""); console.log(cleanedStr); // Output: "photo.png"
Extra Notes
- This regex works with any number of digits (single-digit, double-digit, etc.)—so
_5x10,_1234x5678, all get matched and removed. - If you ever need to adjust the pattern (like matching only numbers within a specific range), feel free to ask for tweaks, but for your stated need, this should cover everything.
内容的提问来源于stack exchange,提问作者Peter Lakatos - appnomads
相关产品推荐
相关产品推荐

