user3681549
user3681549

Reputation:

Regex: Match desired chars at the beginning/end of string

I need a regex to match exactly 'AB' chars set at the beginning or at the end of the string and replace them with ''. Note: it should not match parts of that chars set, only if it occurs whole.

  1. So if I have 'AB Some AB company name AB', it should return 'Some AB company name'.
  2. If I have 'Balder Storstad AB', it should remove only 'AB' and not the 'B' at the beginning because it is not whole 'AB', only the part of it.

What I tried is:

name.replace(/^[\\AB]+|[\\AB]+$/g, "");

And it is OK until single "A" or "B" encountered at the beginning or end of the string. If test string is 'Balder Storstad AB' it matches both 'B' at the beginning and 'AB' at the end and returns 'alder Storstad'. It should skip single 'B' or single 'A' at the beginning or end.

What is wrong in my regex?

EDIT:

I forgot to add this. If test strings are: "ABrakadabra AB" or "Some text hahahAB" or "ABAB text text textABAB"

"AB" should not be matched because they are not separate "AB" groups but part of other word.

Upvotes: 7

Views: 8985

Answers (1)

Djaouad
Djaouad

Reputation: 22776

var rgx = /(^AB\s+)|(\s+AB$)/g;

console.log("AB Some AB company name AB".replace(rgx, ""));

console.log("Balder Storstad AB".replace(rgx, ""));

console.log("ABrakadabra AB".replace(rgx, ""));

console.log("Some text hahahAB".replace(rgx, ""));

console.log("ABAB text text textABAB".replace(rgx, ""));

Explanation :

(^AB\s+) // AB at the beginning (^) with some spaces after it
| // Or
(\s+AB$) // AB at the end ($) with some spaces before it

Upvotes: 6

Related Questions