假设我有string = 'all these words are three characters orr longer'
我想检查一下
if (string.someWayToCheckAllWordsAre3CharactersOrLonger) {
alert("it's valid!");
}
我该怎么做?
答案 0 :(得分:4)
将字符串拆分为数组,然后使用every检查每个单词是否超过3个字符。
var string = 'all these words are three characters orr longer';
// Using regex \s+ to split the string, so only words are get in the array
string.trim().split(/\s+/).every(e => e.length >= 3);
答案 1 :(得分:1)
这样的事情
var string = "all these words are three characters orr longer";
var words = string.split(' ');
var allWordsAreLongerThanThreeChars = true;
for(var i=0;i<words.length;i++){
if(words[i].length < 3){
allWordsAreLongerThanThreeChars = false;
return;
}
}
答案 2 :(得分:0)
两个简单的步骤:使用.split()
将字符串拆分为数组,循环遍历数组并使用.length()
检查每个单词的长度。希望这可以帮助。
var string = 'all these words are three characters orr longer';
var stringArray = string.split(" ");
for (var i = 0; i < stringArray.length; i++){
if(stringArray[i].length >= 3) {
alert(stringArray[i]);
}
};