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.
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
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.
[a-zA-Z]
means any letter from a
to z
or from A
to Z
). ^
) 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
).\
if you preferIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With