Cleary
Cleary

Reputation: 29

How to remove digits based on their length

I only want it to remove if multiple numbers in a row is found greater than 2 in a row in string.

Example, 780 <-- 3 digits, 4880 <-- 4 digits (would remove these from string)

But if 2 digits, example 24 <-- digits, it does not remove

Example, if text is

Dell Model 23506 Laptop M2

How to write replace function to remove the "23506" from above, so the end result is:

Dell Model Laptop M2

Example script template

var item = "Dell Model 23506 Laptop M2";

var item2 = replaceAll(item, XXNUMBERSTOREMOVEXX, "");

Upvotes: 2

Views: 351

Answers (2)

Marios
Marios

Reputation: 27380

Solution:

Although you should accept the other answer which is much cleaner, here is my approach:

function myFunction() {

  const item = 'Dell Model 23506 Laptop M2';
  const numbers = item.match(/(?<=\s+).\d+(?=\s+)/gs)[0]; 
  const item2 = numbers.length>2?item.replace(numbers, ""):item;   
  Logger.log(item2);
}

Upvotes: 2

TheMaster
TheMaster

Reputation: 50654

Use with String.replace:

const item = "Dell Model 23506 Laptop M2";
const item2 = item.replace(/\d{3,}/g, "");
console.log(item2)

  • \d{3,} - 3 or more digits

Upvotes: 5

Related Questions