0

I have the following javascript regex...

.replace("/^(a-zA-Z\-)/gi", '');

It isn't complete... in fact it's wrong. Essentially what I need to do is take a string like "XJ FC-X35 (1492)" and remove the () and it's contents and the whitespace before the parenthesis.

2 Answers 2

4
replace(/^(.*?)\s?\(([^)]+)\)$/gi, "$1$2")

Takes XJ FC-X35 (1492) and returns XJ FC-X351492.

Remove the $2 to turn XJ FC-X35 (1492) into XJ FC-X35, if that's what you wanted instead.

Long explanation

^   // From the start of the string
(   // Capture a group ($1)
.*? // That contains 0 or more elements (non-greedy)
)   // Finish group $1
\s? // Followed by 0 or 1 whitespace characters
\(  // Followed by a "("
(   // Capture a group ($2)
[   // That contains any characters in the following set
^)  // Not a ")"
]+  // One or more times
)   // Finish group $2
\)$ // Followed by a ")" followed by the end of the string.
Sign up to request clarification or add additional context in comments.

3 Comments

+1 for a robust regexp, and for providing alternatives depending on what the OP meant. But do you really need to match and replace the initial ^(.*?)? Why not just omit it?
@LarsH - Habit more than anything else. I always prefer, when dealing with regular expressions to make sure that I'm grabbing what I want, rather than removing what I don't (whitelist, don't blacklist). You are correct though - the ^(.*?) and $ could be removed without harm resulting in the easier to read replace(/\s?\(([^)]+)\)/gi, "$1") -- and it's up to the fair reader to choose the better way.
nice bit-by-bit explanation. Btw I preferred your earlier \s* over \s?, since the OP's "the whitespace" is pretty ambiguous as to cardinality. I would have put \s+ but you may be right.
2

Try this:

x = "XJ FC-X35 (1492)"
x.replace(/\s*\(.*?\)/,'');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.