Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace all occurrences of character except in the beginning of string (Regex)

I'm trying to get rid of all minuses/dashes in a string number, except the first occurrence. After fiddling with Regex (JavaScript) for half an hour, still no results. Does anyone know the fix?

Given:

-123-45-6

Expected:

-123456

Given:

789-1-0

Expected:

78910

like image 543
Mark El Avatar asked Feb 28 '14 11:02

Mark El


People also ask

How do you replace all occurrences of a regex pattern in a string?

sub() method will replace all pattern occurrences in the target string. By setting the count=1 inside a re. sub() we can replace only the first occurrence of a pattern in the target string with another string. Set the count value to the number of replacements you want to perform.

How do you replace all occurrences of a character in a string?

To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag. replaceAll() method is more straight forward.

Can regex replace characters?

RegEx can be effectively used to recreate patterns. So combining this with . replace means we can replace patterns and not just exact characters.

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.


2 Answers

This one will do as well(it means dashes not at the beginning of the string):

(?!^)-

Example:

text = "-123-45-6".replace(/(?!^)-/g, "");
like image 153
Sabuj Hassan Avatar answered Sep 29 '22 20:09

Sabuj Hassan


A simple solution :

s = s.replace(/(.)-/g,'$1')
like image 43
Denys Séguret Avatar answered Sep 29 '22 21:09

Denys Séguret