Search code examples
javascriptreactjsregexregex-groupregexp-replace

replace all special characters expect first occurrence of +


I want to replace everything other than numeric char from a string, but if + appears at the starting of the string it should be ignored. for example

1234++!@#$%^&*()_+=-;',.><:" becomes 1234
+1234 becomes +1234
++++1234 becomes +1234
+1234++!@#$%^&*()_+=-;',.><:" becomes +1234
+1234++!@#$%^&*()_+=-;',.><:" becomes +1234
+1234ABCabc++!@#$%^&*()_+=-;',.><:" becomes +1234
1234ABCabc++!@#$%^&*()_+=-;',.><:" becomes 1234
Aa1234ABCabc++!@#$%^&*()_+=-;',.><:" becomes 1234
a+1234ABCabc++!@#$%^&*()_+=-;',.><:" becomes 1234
1+1234ABCabc++!@#$%^&*()_+=-;',.><:" becomes 11234

can you please suggest?


Solution

  • You can try:

    str.replace(/((?<!^)\D)|(^[^+0-9])/g, '');

    This replaces (with nothing):

    • any non-digit that is not at the start of the string.
    • any non-digit except + that is at the start of the string.