Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex string replace

I am trying to do a basic string replace using a regex expression, but the answers I have found do not seem to help - they are directly answering each persons unique requirement with little or no explanation.

I am using str = str.replace(/[^a-z0-9+]/g, ''); at the moment. But what I would like to do is allow all alphanumeric characters (a-z and 0-9) and also the '-' character.

Could you please answer this and explain how you concatenate expressions.

like image 297
Patrick Avatar asked Dec 05 '12 15:12

Patrick


People also ask

Does string replace take regex?

The Regex. Replace(String, String, MatchEvaluator, RegexOptions) method is useful for replacing a regular expression match in if any of the following conditions is true: The replacement string cannot readily be specified by a regular expression replacement pattern.

What is regex replace?

The RegEx Replace processor provides a way to perform advanced text replacements by matching text values to a regular expression, and replacing the matching value with a specific value, or with a value derived from the matched text - for example replacing the whole of a String that matched a regular expression with ...

What is $1 in regex replace?

For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.

How do I replace a string in a string?

The replace() method searches a string for a value or a regular expression. The replace() method returns a new string with the value(s) replaced. The replace() method does not change the original string.


1 Answers

This should work :

str = str.replace(/[^a-z0-9-]/g, ''); 

Everything between the indicates what your are looking for

  1. / is here to delimit your pattern so you have one to start and one to end
  2. [] indicates the pattern your are looking for on one specific character
  3. ^ indicates that you want every character NOT corresponding to what follows
  4. a-z matches any character between 'a' and 'z' included
  5. 0-9 matches any digit between '0' and '9' included (meaning any digit)
  6. - the '-' character
  7. g at the end is a special parameter saying that you do not want you regex to stop on the first character matching your pattern but to continue on the whole string

Then your expression is delimited by / before and after. So here you say "every character not being a letter, a digit or a '-' will be removed from the string".

like image 126
koopajah Avatar answered Sep 24 '22 12:09

koopajah