Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove or replace Alphabets from specific position in Regex

I want to remove the Alphabets "Country Names" and bracket "()" from my Country Code selection drop-down menu. but the problem is I can't find the perfect match REGEX for this.

<span class="flag-icon flag-icon-afg"></span> Afganistan (+93)
<span class="flag-icon flag-icon-bgd"></span> Bangladesh (+880)
<span class="flag-icon flag-icon-ind"></span> India (+91)

replace(/[()A-Za-z]{45,100}/g, '');

This pattern is also removing the alphabets of my tag which creates problem for me because the span tag contain SVG country flag icons, for this I want to remove the alphabets from 45th position and remove only the country names and () after selecting a drop-down option.

Output I'm getting -

Flag-icon Country-Name +93 (It just removing the brackets not country name)

Output I want -

Flag-icon +93

DATA.replace(/[()A-Za-z]{45,100}/g, '');
like image 718
Gupa Dutta Avatar asked Dec 01 '25 12:12

Gupa Dutta


2 Answers

Instead of using an exact offset to start the match, you could capture the ` tag in the current data in group 1, and capture the format of the number between parenthesis in group 2.

The use those 2 groups in the replacement.

(<span\b[^<>]*><\/span>\s*)\w+(?:\s+\w+)*\s*\((\+\d+)\)

The pattern matches:

  • (<span\b[^<>]*><\/span>\s*) Capture from <span>...</span> in group 1
  • \w+(?:\s+\w+)*\s* Match word chars optionally repeated by spaces and word chars
  • \( Match (
    • (\+\d+) Capture + and 1+ digits in group 2
  • \) Match )

See a regex demo with the capture group data.

const regex = /(<span\b[^<>]*><\/span>\s*)\w+(?:\s+\w+)*\s*\((\+\d+)\)/g;
const str = `<span class="flag-icon flag-icon-afg"></span> Afganistan (+93)
<span class="flag-icon flag-icon-bgd"></span> Bangladesh (+880)
<span class="flag-icon flag-icon-ind"></span> India (+91)`;

console.log(str.replace(regex, `$1$2`));
like image 85
The fourth bird Avatar answered Dec 03 '25 03:12

The fourth bird


I think the problem you're facing is that you're trying to remove characters around a thing instead of just matching that thing, which would be an easier task where you could use regex capture groups. Not sure I fully understood the inputs and outputs but for each row you could do:

const formatRow = (input) => {
  const flagMatch = input.match(/flag-icon-\w+/);
  const flag = flagMatch && flagMatch[0];

  const numberMatch = input.match(/\((.*)\)/);
  const number = numberMatch && numberMatch[1]; // 1 is index of capture group

  return `${flag} ${number}`
}

// e.g
formatRow('<span class="flag-icon flag-icon-afg"></span> Afganistan (+93)'); // output: 'flag-icon-afg +93'
like image 40
Jackson Christoffersen Avatar answered Dec 03 '25 05:12

Jackson Christoffersen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!