gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 06:58:19 25 4
gpt4 key购买 nike

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

我如何在 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 这个头脑更快(真||假)比(假||真)

此时我们可以添加另一个概念,运算符总是返回计算中的最后一个元素

(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
}

关于javascript - 从字母数字字符串中删除数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30663518/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com