从字符串中删除元音
Remove the Vowels from a String in JavaScript
要从字符串中删除元音,请replace()
使用以下正则表达式调用该方法 – /[aeiou]/gi
,例如
str.replace(/[aeiou]/gi, '')
。该replace()
方法将返回一个新字符串,其中原始字符串中的任何元音都被替换为空字符串。
索引.js
const str = 'hello world'; const noVowels = str.replace(/[aeiou]/gi, ''); console.log(noVowels); // 👉️ hll wrld
我们将以下 2 个参数传递给
String.replace
方法:
- 要在字符串中匹配的正则表达式
- 每场比赛的替换
正斜杠/ /
标记正则表达式的开始和结束。
The part in the square brackets
[]
is called a character class and matches any of the characters in the brackets, in our case – any vowel.For example, [abc]
matches the characters a
, b
and c
.
We used the g
(global) flag because we want to match all occurrences of a
vowel in the string and not just the first occurrence.
The i
flag is used to make the search case insensitive. These two regular
expressions are the same:
/[aeiou]/gi
/[aeiouAEIOU]/g
If you need a regex cheatsheet, check out
this one
from MDN.
The second parameter we passed to the replace()
method is the replacement
string for each match. Because we want to remove each vowel, we replace it with
an empty string.
请注意,该
replace()
方法不会更改原始字符串,它会返回一个新字符串。字符串在 JavaScript 中是不可变的。