正在从字母数字字符串中删除数值

Removing numeric values from alphanumeric string

本文关键字:字符串 删除 数字字符 数字      更新时间:2023-09-26

我想从字符串中删除所有数值但前提是字符串至少包含一个字母。

我如何在JavaScript中做到这一点?

例如

var s = "asd23asd"

则结果必须为asdasd

但是,如果

var s = "123123"

那么结果必须是123123,因为字符串中并没有任何字母。

function filter(string){
     var result = string.replace(/'d/g,'')
     return result || string;
}

或直接

var newString = string.replace(/'d/g,'') || string;

为什么||有效

||和&是条件运算符,并且确保您在if、while。。。

如果你做了像这样的事情

var c1 = false, c2 = true, c3= false, c4 = true;
if( c1 || c2 || c3 || c4) {
}

此评估将在第一个有效或无效的时刻停止。

这个心,评估在c2停止这个心,速度更快(true||false(比(false||true(

在这一点上,我们可以添加另一个概念,操作员总是返回评估中的最后一个元素

(false||'hey'||true(返回'hey',记住在JS中'hey`是true,但''是false

有趣的例子:

var example = {
  'value' : {
     'sub_value' : 4
  }
}
var test = example && example.value && example.value.sub_value;
console.log(test) //4
var test_2 = example && example.no_exist && example.no_exist.sub_value;
console.log(test_2) //undefined

var test_3 = example.valno_existue.sub_value; //exception
function test_function(value){
   value = value || 4; //you can expecify default values
}

你可以试试这个。首先检查单词是否包含任何字母表,如果包含,则替换。

var s = "asd23asd";
if(/'w+/.test(s))
    s = s.replace(/'d+/g, '');
([a-zA-Z]+)'d+|'d+(?=[a-zA-Z]+)

你可以试试这个。替换为$1。请参阅演示。

https://regex101.com/r/nS2lT4/27

Javascript代码

  var txt='asd23ASd3';
  if(parseInt(txt))
      var parsed=txt;
  else
      var parsed=txt.replace ( /[^a-zA-Z]/g, '');
  console.log(parsed)