7

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.

  • Square brackets in regex are for character classes: it will match ANY one of the characters listed. In your case, a backslash (for some reason), an `A`, or a `B`. By adding the `+` quantifier, you are also removing any other matching characters until it finds one that doesn't match. For instance, "ABBBAAA\BBB\ text" would become " text". – Brian Stephens Sep 05 '17 at 13:15
  • Possible duplicate of [Trim specific character from a string](https://stackoverflow.com/questions/26156292/trim-specific-character-from-a-string) – shA.t Sep 05 '17 at 13:29

1 Answers1

6

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
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
  • If fails if test string is "ABABSome AB company name AB" because it matches first "AB" and returns "ABsome AB company name". It should match only if it is "AB" alone and not the part of other word on beginning or end. –  Sep 05 '17 at 13:41
  • So for `"ABABSome AB company name AB"` you want it to return `"Some AB company name"`? – DjaouadNM Sep 05 '17 at 13:43
  • I want to return "ABABSome AB company name" . Onyl to match "AB" if it is on beginning or end and not the part of other word. In this test string, "AB" is part of "ABABSome " at the beginning and it should be skiped. Same if "ABalder Storstad ABAB" - it shouldn't match because there is no "AB" alone. –  Sep 05 '17 at 13:47
  • Thank you very much, it seems to be OK now. –  Sep 05 '17 at 13:58