Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
747 views
in Technique[技术] by (71.8m points)

javascript - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

var rgx = /(^ABs+)|(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, "")
);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...