Replace Pipe and Comma with Regex in Javascript

2020-08-21 03:01发布

问题:

I'm sitting here with "The Good Parts" in hand but I'm still none the wiser.

Can anyone knock up a regex for me that will allow me to replace any instances of "|" and "," from a string.

Also, could anyone point me in the direction of a really good resource for learning regular expressions, especially in javascript (are they a particular flavour??) It really is a weak point in my knowledge.

Cheers.

回答1:

str.replace(/(\||,)/g, "replaceWith") don't forget the g at the end so it seaches the string globally, if you don't put it the regex will only replace the first instance of the characters.

What is saying is replace | (you need to escape this character) OR(|) ,

Nice Cheatsheet here



回答2:

The best resource I have found if you really want to understand regular expressions (and the special caveats or quirks of any of a majority of the implementations/flavors) is Regular-Expressions.info.

If you really get into regular expressions, I would recommend the product called RegexBuddy for testing and debugging regular expressions in all sorts of languages (though there are a few things it does not quite support, it is rather good overall)

Edit:

The best way (I think, especially if you consider readability) is using a character class rather than alternation (i.e.: [] instead of |)

use:

var newString = str.replace(/[|,]/g, ";");

This will replace either a | or a , with a semicolon

The character class essentially means "match anything inside these square brackets" - with only a few exceptions.

  • First, you can specify ranges of characters ([a-zA-Z] means any letter from a to z or from A to Z).
  • Second, putting a caret (^) at the beginning of the character class negates it - it means anything not in this character class ([^0-9] means any character that is not from 0 to 9).
  • put the dash at the beginning and the caret at the end of the character class to match those characters literally, or escape them anywhere else in the class with a \ if you prefer