简体   繁体   English

替换所有特殊字符,期望第一次出现 +

[英]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?你能建议吗?

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: 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.请更具体地说明您需要什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM