使用for循环查找字符串中的特定字符
Using for loop to find specific characters in string
我正在尝试Eloquent Javascript一书的函数章节中的bean计数示例。我的函数是返回一个空白。
如果不给我完整的答案(我正在学习这个例子),有人能告诉我为什么我的代码没有打印任何文本吗?"
var string = "donkey puke on me boot thar be thar be!";
for (var i = 0; i <= string.length; i++);
function getB(){
if (string.charAt(i) == "b")
return i;
else return "";
}
console.log(getB());
您尝试实现此功能的方式有问题。首先,我认为最好有一个函数,它接受string
和char
作为参数,以便随时调用它。
调用示例:
getChar('this is my custom string', 'c') -> it should search character `c` in `this is my custom string`
getChar('this is another custom string', 'b') -> it should search character `b` in `this is another custom string`
实施示例:
var getChar = function(string, char){
for(var i=0;i<string.length;i++)
{
if(string.charAt(i)==char) console.log(i);
}
}
现在,尝试使其不区分大小写,而不是console.log
,输出尝试返回一个字符位置为
使用这个,
var string = "donkey puke on me boot thar be thar be!";
for (var i = 0; i <= string.length; i++) {
if (string.charAt(i) == "b") {
console.log(i);
}
}
如果你想打印你的值所在的每个位置,你可以编程如下:
var string = "donkey puke on me boot thar be thar be!";
for (var i = 0; i <= string.length; i++)
{
getChar(i, "b");
}
function getChar(i, input)
{
if (string.charAt(i) == input)
console.log(i);
}
另一个例子:收集所有b位置:
var string = "donkey puke on me boot thar be thar be!";
function getB(string){
var placesOfB = [];
for (var i = 0; i < string.length; i++) {
if (string.charAt(i) == "b") {
placesOfB.push(i);
}
}
return placesOfB;
}
console.log(getB(string));
提示:您的for
没有正文(将;
放在它后面只是循环而不做任何事情)。。。并且在CCD_ 6内部定义函数是没有意义的。
在不给你完整答案的情况下,我只给你一些提示:1.你的for循环不完整——它什么都没做。2.您的getB()函数需要接受字符串参数才能对其执行一些操作。3.if.else语句没有左括号和右括号{}
相关文章:
- 如何将字符串拆分为字符,但在javascript中保留空格
- 如何显示字符串中最多 200 个字符
- 我想在Javascript中探索类似C语言的字符串的整个字符
- 如何用jquery替换字符串中可能变化的字符
- 通过跳过拆分字符在 javascript 中拆分字符串
- 使用正则表达式匹配长度为六个字符的字母数字字符串
- 字符串替换-不支持格式字符'}'
- 到UpperCase字符串Javascript中的特定字符索引
- 用类javascript包装span标记中字符串中的字符索引
- 将字符串分组为n个字符的块,并应用替换
- 如何检查一个字符串的所有字符是否都存在于另一个字符串中
- 在字符串列表中搜索任何出现的单词,如果单词的第一个字符匹配,则高亮匹配单词.Javascript正则表达式
- Javascript-正则表达式,用于在未转义字符上拆分字符串,例如|,但忽略|
- Regex-从字符第N次出现到字符串末尾的匹配
- Visual Studio 2010跳转到下一个任意字符/字符串
- 估计存储在 localStorage (Javascript) 中的 10,000 个字符字符串的大小
- 字符字符串中最后一个单词的第一个字母
- 匹配任何字符字符串的正则表达式,最多为“/”Javascript
- 将特殊字符字符串到 JSON 字符串化非法令牌中
- 在javascript中计算精确的字符字符串高度