我在FreeCodeCamp上遇到了一些挑战,但我迷失在要求检查“回文检查”的基本挑战中。在解决方案中,我必须执行以下操作:
str = str.replace(/[^a-zA-Z]/g, '').toLowerCase();
但是我不明白我必须使用replace方法和正则表达式的原因。
有人可以帮助我吗?
使用此代码:
str.replace(/[^a-zA-Z]/g, '').toLowerCase()
您将摆脱掉所有不是AZ和az字母的字符,然后将替换后的字符串设置为小写。在^
一开始的字符类的[
..]
像[^...]
手段not this characters
。因此,[a-z]
意味着匹配从a到z的字母,而[^a-z]
意味着匹配从a到z的字母以外的任何字母
有很多在线正则表达式工具可以解释这些模式。在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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句