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
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.
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.
RegEx can be effectively used to recreate patterns. So combining this with . replace means we can replace patterns and not just exact characters.
For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.
This one will do as well(it means dashes not at the beginning of the string):
(?!^)-
Example:
text = "-123-45-6".replace(/(?!^)-/g, "");
A simple solution :
s = s.replace(/(.)-/g,'$1')
If 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