我在FreeCodeCamp上做了一些挑战,我在基本的挑战中迷失了方向 要求检查回文。在解决方案中,我必须执行以下操作:
str = str.replace(/[^a-zA-Z]/g, '').toLowerCase();
但我不明白我必须使用替换方法和正则表达式的原因。
有人可以帮助我吗?
答案 0 :(得分:2)
使用此代码:
str.replace(/[^a-zA-Z]/g, '').toLowerCase()
你正在摆脱所有不是来自A-Z和a-z的字母的字符,然后你将被替换的字符串设置为小写字母。字符类^
开头的[
.. ]
,如[^...]
,表示not this characters
。因此,[a-z]
表示来自a到z 的匹配字母,而[^a-z]
表示匹配除a到z之间的任何字母
<强> Demo 强>
有很多在线正则表达式工具可以解释这些模式。从Regex101,您可以看到:
/[^a-zA-Z]/g
[^a-zA-Z] match a single character not present in the list below
a-z a single character in the range between a and z (case sensitive)
A-Z a single character in the range between A and Z (case sensitive)
g modifier: global. All matches (don't return on first match)