从字符串中删除字符 [英] Remove characters from a string

查看:102
本文介绍了从字符串中删除字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以通过JavaScript从字符串中删除字符的不同方法有哪些?

What are the different ways I can remove characters from a string in JavaScript?

推荐答案

使用用正则表达式替换()是最灵活/最强大的。它也是全局替换JavaScript中每个搜索模式实例的唯一方法。 replace()的非正则表达式变体只会替换第一个实例。

Using replace() with regular expressions is the most flexible/powerful. It's also the only way to globally replace every instance of a search pattern in JavaScript. The non-regex variant of replace() will only replace the first instance.

例如:

var str = "foo gar gaz";

// returns: "foo bar gaz"
str.replace('g', 'b');

// returns: "foo bar baz"
str = str.replace(/g/gi, 'b');

在后一个示例中,尾随 / gi 表示不区分大小写和全局替换(意味着不仅应该替换第一个实例),这是您在替换字符串时通常需要的。

In the latter example, the trailing /gi indicates case-insensitivity and global replacement (meaning that not just the first instance should be replaced), which is what you typically want when you're replacing in strings.

删除字符,请使用空字符串替换:

To remove characters, use an empty string as the replacement:

var str = "foo bar baz";

// returns: "foo r z"
str.replace(/ba/gi, '');

这篇关于从字符串中删除字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆