I am in need of a regular expression (regex) that can precisely match the char set 'AB'
only if it is at the beginning or end of a string, and then replace it with an empty string. It is important to note that the regex should not match parts of the char set, only the whole occurrence.
- For example, if the input is
'AB Some AB company name AB'
, the output should be'Some AB company name'
. - If the input is
'Balder Storstad AB'
, only the 'AB' at the end should be removed, while the 'B' at the beginning should remain untouched because it is not the complete 'AB' set.
This is what I have tried so far:
name.replace(/^[\\AB]+|[\\AB]+$/g, "");
However, this regex works fine unless there is a single "A" or "B" encountered at the beginning or end of the string. For instance, with the test string 'Balder Storstad AB'
, both 'B' at the start and 'AB' at the end are matched, resulting in 'alder Storstad'
. The intention is to ignore single 'B' or 'A' characters at the edges.
What could be wrong with my regex?
EDIT:
I would like to mention one more thing. If the test strings are: "ABrakadabra AB", "Some text hahahAB", or "ABAB text text textABAB"
The "AB" sequences in these examples should not be replaced as they are part of other words and not separate instances of "AB".