0

I've got three working regexp's,

string.replace(\catalogue\g, "") // replace a the word catalogue

string.replace(/[/:]/g, "") // replace the characters /, :

string.replace(\20%\g, "") // replace '20%'

Instead of replacing the string three times, I want to combine my regexp's.

Wanted result = 'removethewordnow';

var string = 'rem:ove20%the/word:catalogue20%now';

My latest try was:

string.replace(/\catalogue\b|[/20%:]/g, ""); // works, but catalouge is unaffected and 20% isn't combined as a word
3
  • I could be wrong, but I feel you're missing an "or" (|) statement Commented Mar 5, 2012 at 14:37
  • it's right after the B - b | [letters] Commented Mar 5, 2012 at 14:38
  • I wasn't escaping the c on purpose, just the whole word "catalogue" - but the first one actually works just fine. Commented Mar 5, 2012 at 14:50

6 Answers 6

2

Off the top of my head:

string.replace(/(catalogue|[\/:]|20%)/g,"");
Sign up to request clarification or add additional context in comments.

1 Comment

Characters inside [] don't need backslashing, don't they?
2

Just use an alternative, i.e. separate each of the regular expressions you had before by the alternation operator |:

catalogue|20%|[/:]

Also note that you cannot just combine character classes and literal strings in the way you have done there. Above naïve combination works and everything beyond that might be optimisation (even if it can't be optimised further in this case) – but that only works if you don't change the language described by the regex.

Comments

2

You seem to be having a typo there (\c), also you don't want 20% inside the character class (and you should escape the slash). You also need to remove the word boundaries if you want to allow catalogue20% to match - there is no boundary between catalogue and 20, therefore the \b fails:

string.replace(/catalogue|20%|[\/:]/g, "");

Comments

1
var string = 'rem:ove20%the/word:catalogue20%now';

string.replace(/([:/]|20%|catalogue)/g, '');

Comments

0

\b refers to a word boundary, but your word catalogue is mixed with other words. So your regex should be:

string.replace(/catalogue|[\/20%:]/g, "");

Also do escape the / with \/.

1 Comment

I read that you don't need to escape / if it's in the beginning or end of the characters, which it was in this case [/:20%]
0
string.replace(/catalogue|20%|[/:]/g, '')

1 Comment

why would you prefer to encapsule the words in brackets? both (catalogue)|(20%) and catalogue|20% seem to work..

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.