Javascript 从字符串中删除字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4846978/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove characters from a string
提问by Skizit
What are the different ways I can remove characters from a string in JavaScript?
在 JavaScript 中从字符串中删除字符有哪些不同的方法?
回答by Dave Ward
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.
replace()
与正则表达式一起使用是最灵活/最强大的。这也是全局替换 JavaScript 中搜索模式的每个实例的唯一方法。的非正则表达式变体replace()
只会替换第一个实例。
For example:
例如:
var str = "foo gar gaz";
// returns: "foo bar gaz"
str.replace('g', 'b');
// returns: "foo bar baz"
str = str.replace(/g/gi, 'b');
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.
在后一个示例中,尾随/gi
表示不区分大小写和全局替换(意味着不仅应该替换第一个实例),这是您在字符串中替换时通常想要的。
To removecharacters, use an empty string as the replacement:
要删除字符,请使用空字符串作为替换:
var str = "foo bar baz";
// returns: "foo r z"
str.replace(/ba/gi, '');
回答by Kamil Kie?czewski
ONELINERwhich remove characters LIST (more than one at once) - for example remove +,-, ,(,)
from telephone number:
ONELINER删除字符 LIST(一次多个) - 例如+,-, ,(,)
从电话号码中删除:
var str = "+(48) 123-456-789".replace(/[-+()\s]/g, ''); // result: "48123456789"
We use regular expression [-+()\s]
where we put unwanted characters between [
and ]
我们使用正则表达式[-+()\s]
,将不需要的字符放在[
和]
(the "\s
" is 'space' character escape - for more info google 'character escapes in in regexp')
(“ \s
” 是“空格”字符转义 - 有关更多信息,请参阅谷歌“正则表达式中的字符转义”)
回答by atamata
I know this is old but if you do a split then join it will remove all occurrences of a particular character ie:
我知道这是旧的,但是如果您进行拆分,则加入它将删除所有出现的特定字符,即:
var str = theText.split('A').join('')
will remove all occurrences of 'A' from the string, obviously it's not case sensitive
将从字符串中删除所有出现的 'A',显然它不区分大小写
回答by Nicholas Koskowski
Another method that no one has talked about so far is the substr method to produce strings out of another string...this is useful if your string has defined length and the characters your removing are on either end of the string...or within some "static dimension" of the string.
到目前为止没有人讨论过的另一种方法是 substr 方法从另一个字符串中生成字符串...如果您的字符串已定义长度并且您删除的字符位于字符串的任一端...或在字符串内,这将很有用字符串的一些“静态维度”。