replace all special characters expect first occurrence of +

Viewed 47

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?

2 Answers

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.

This extracts numbers from a string, including an optional leading +:

var tests = [
  '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
];

tests.forEach(str => {
  console.log(str + ' => ' + str.replace(/^.*?(\+?[0-9]+).*$/, '$1'));
});

Output:

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

Your described objective and last example contradict each other. Please be more specific what you need.

Related