[英]How can I pass this JavaScript CodeWars challenge?
In this challenge I have to replace every "WUB"
in the string with a space. 在此挑战中,我必须用空格替换字符串中的每个
"WUB"
。 If there is more than one "WUB"
in a row then I have to replace all of them with a single space. 如果连续有多个
"WUB"
,那么我必须用一个空格替换所有它们。 For example, entering "WUBAPPLEWUBWUBBANANAWUBWUBWUBCARROT"
would return "APPLE BANANA CARROT"
. 例如,输入
"WUBAPPLEWUBWUBBANANAWUBWUBWUBCARROT"
将返回"APPLE BANANA CARROT"
。
Also I have to get rid of heading and trailing spaces at the beginning and end of the string. 另外,我还必须摆脱字符串开头和结尾的开头和结尾空格。 I was wondering how I could change my code to pass these requirements, I'm still pretty new to JavaScript.
我想知道如何更改代码来满足这些要求,但我对JavaScript还是很陌生。 Thanks.
谢谢。
function songDecoder(song){
var regex = /wub/gi;
song = song.toLowerCase().replace(regex, ' ')
return song.toUpperCase()
}
You're on right track all you need to do is add a quantifier to match more than one WUB
in continuation, and you can also avoid first converting to lowercase and than converting back to uppercase after match as we are using i
flag which will take care of case insensitivity 您走在正确的轨道上,您需要做的就是添加一个量词以匹配多个连续的
WUB
,并且您还可以避免先转换为小写字母,然后避免匹配后转换回大写字母,因为我们使用的是i
标志,不区分大小写
(?:wub)+
let str = "WUBAPPLEWUBWUBBANANAWUBWUBWUBCARROT" function songDecoder(song){ var regex = /(?:wub)+/gi; song = song.replace(regex, ' ') return song.trim() } console.log(songDecoder(str))
As you are new so you need to understand the symbols of using regular expression: 由于您是新手,因此您需要了解使用正则表达式的符号:
g modifier: global. g修饰符:全局。 All matches (don't return after first match)
所有比赛(第一次比赛后不返回)
i modifier: insensitive. i修饰符:不敏感。 Case insensitive match (ignores case of [a-zA-Z])
不区分大小写的匹配(忽略[a-zA-Z]的大小写)
In your case though i
is immaterial as you dont capture [a-zA-Z]
. 在您的情况下,尽管您没有捕获
[a-zA-Z]
但i
并不重要。
For input like !@#$?
输入像
!@#$?
if g
modifier is not there regex will return first match !
如果
g
修饰符不存在,则正则表达式将返回第一个匹配项!
See here . 看这里 。
If g
is there it will return the whole or whatever it can match. 如果
g
存在,它将返回整数或它可以匹配的任何值。 See here 看这里
let var = "WUBAPPLEWUBWUBBANANAWUBWUBwubCARROT";
function songDecoder(song){
var regex = /(?:wub)+/gi;
song = song.replace(regex, ' ')
return song.trim()
}
alert(songDecoder(str)); alert(songDecoder(str));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.