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

pd1*_*176 1 javascript regex

我想从字符串中删除所有数值但仅当字符串包含至少一个字母时.

我怎样才能在JavaScript中执行此操作?

例如

var s = "asd23asd"
Run Code Online (Sandbox Code Playgroud)

那么结果必须是asdasd

但是如果

var s = "123123"
Run Code Online (Sandbox Code Playgroud)

然后结果必须是123123,因为字符串没有任何字母.

Raú*_*tín 13

function filter(string){
     var result = string.replace(/\d/g,'')
     return result || string;
}
Run Code Online (Sandbox Code Playgroud)

或直接

var newString = string.replace(/\d/g,'') || string;
Run Code Online (Sandbox Code Playgroud)

为什么|| 作品

|| 和&是条件运算符,并确保你使用if,而...

如果你喜欢的话

var c1 = false, c2 = true, c3= false, c4 = true;
if( c1 || c2 || c3 || c4) {
}
Run Code Online (Sandbox Code Playgroud)

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

这个心态认为评价在c2中停止这种思维比(假||假)更快(真||假)

此时我们可以添加另一个概念,操作符返回始终是评估中的最后一个元素

(假||'嘿'|| true)返回'嘿',记住在JS'嘿'是真的但是''是假的

有趣的例子:

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
}
Run Code Online (Sandbox Code Playgroud)

  • 很好用``|` (2认同)