0

How do I strip numbers that are not next to letters in a string, for example

"13 Some Street, Some Place, PE15 0TZ"

In this case I want to remove the 13 only, not the numbers in the post code.

"M1, Some Place, PE15 0TZ"

In the above case it would not remove anything as all numbers are next to letters.

I have found lots of code that can strip numbers from strings (.replace(/\d+/g, '')) but none that take its neighbours into account

Carl Zulauf
  • 39,378
  • 2
  • 34
  • 47
Chris
  • 26,744
  • 48
  • 193
  • 345

2 Answers2

4

You could use a word boundary \b on both sides and match one or more digits \d+ to select only 13:

\b\d+\b

const strings = [
  "13 Some Street, Some Place, PE15 0TZ",
  "M1, Some Place, PE15 0TZ",
  "Some Street, Some Place, 15 PE15 0TZ 16",
];
let pattern = /\b\d+\b/g;

strings.forEach((s) => {
  console.log(s.replace(pattern, ""));
});
The fourth bird
  • 154,723
  • 16
  • 55
  • 70
2

Use the following regex to test if a number is surrounded by spaces or the beginning/end of the string:

/(^|\s)\d+(\s|$)/g

examples = ["13 Some Street, Some Place, PE15 0TZ", "M1, Some Place, PE15 0TZ"]
for (var i = 0; i < examples.length; i++)
{
    console.log(
        examples[i].replace(/(^|\s)\d+(\s|$)/g, '$1$2')
    );
}
Jerodev
  • 32,252
  • 11
  • 87
  • 108