如何从javascript中的字符串中删除子字符串?

用户名

我有一个变量的值是03_ButtonAdd。我想从中删除_ButtonAdd。表示我只想要数字值。如何在javascript中做到这一点?

塞布鲁斯

试试这个:

'03_ButtonAdd'.replace('_ButtonAdd', '');
// returns: '03'

String.prototype.replace 文档。

假设:

var s = '03_ButtonAdd';

其他一些方法是:

s.substring(0,2);
parseInt(s, 10)   // returns `3`, not `'03'`
/\d+/.exec(s)[0]; // Regex -> get all digits.

还有一些更丑陋/效率低下的替代方案(不要使用这些替代方案):

s.split('_')[0];  // Split at _, get first index of array.

var out = '';
for(var i = 0; i < s.length; i++){
    if(isFinite(s[i])){
        out += s[i];
    }
}                // Seriously, now I'm just messing around, don't use this.

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章