You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何移除字符串中未与字母相邻的数字?

Remove Isolated Digits (Not Adjacent to Letters)

Got it, let's figure out how to solve this! The core idea is we only want to get rid of digits that don't sit next to any letters—so digits paired with a-z/A-Z (either before or after) stay put, while standalone digit groups get removed.

The Regex Solution

Here's a JavaScript function that does exactly what you need, using negative lookarounds in regex to target the right digits:

const stripIsolatedDigits = (inputStr) => {
  // Match digit groups with NO letter before AND NO letter after
  return inputStr.replace(/(?<![a-zA-Z])\d+(?![a-zA-Z])/g, '').trim();
};

Let's Break Down the Regex

Let's unpack (?<![a-zA-Z])\d+(?![a-zA-Z]) to understand why it works:

  • (?<![a-zA-Z]): This is a negative lookbehind—it checks that there's no letter immediately before the digits we're targeting.
  • \d+: Matches one or more consecutive digits (covers single digits or groups like "13").
  • (?![a-zA-Z]): This is a negative lookahead—it checks that there's no letter immediately after the digits.
  • The g flag ensures we replace all matching digit groups, not just the first one.

Test It With Your Examples

Let's plug in your sample strings to verify:

  1. For "13 Some Street, Some Place, PE15 0TZ":
    stripIsolatedDigits("13 Some Street, Some Place, PE15 0TZ");
    // Output: "Some Street, Some Place, PE15 0TZ" (the isolated "13" is gone, zip code digits stay)
    
  2. For "M1, Some Place, PE15 0TZ":
    stripIsolatedDigits("M1, Some Place, PE15 0TZ");
    // Output: "M1, Some Place, PE15 0TZ" (all digits are adjacent to letters, so nothing gets removed)
    

Edge Cases to Keep in Mind

  • Isolated digits with symbols: Strings like "123, 456-789" will have all digit groups removed, since none are next to letters.
  • Digits with one letter neighbor: "5abc" or "xyz7" keep their digits—they only need a letter on one side to stay.
  • Mixed cases: The regex works for both uppercase and lowercase letters, so "A1b" or "9X" are safe.

内容的提问来源于stack exchange,提问作者Chris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:04:44