gene b.
gene b.

Reputation: 11996

JS Regex: Remove Text in Parentheses if starts with digit

Quick JS Regex question. I need a common Regex that will remove the parts in parentheses (incl. parentheses themelves) that start with a digit. Otherwise, that parentheses block stays.

Somehow the below doesn't work. I was expecting

var str1 = "String 1 (12:30am - 5:00pm)";
var str2 = "String 2 (Parentheses) (3:00am - 3:10am)";

console.log(
  str1.replace(/\(^[0-9].*$\)/g, '').trim() + 
  "\n" + 
  str2.replace(/\(^[0-9].*$\)/g, '').trim()
);

Upvotes: 1

Views: 43

Answers (1)

Ori Drori
Ori Drori

Reputation: 192016

The start ^ and end $ symbols refer to the start and end of the input string. Remove them.

var str1 = "String 1 (12:30am - 5:00pm)";
var str2 = "String 2 (Parentheses) (3:00am - 3:10am)";

function clearWithNumbers(str) {
  return str.replace(/\(\d.*\)/g, '').trim();
}

console.log(clearWithNumbers(str1));

console.log(clearWithNumbers(str2));

Upvotes: 1

Related Questions