function writeDocument(variable) {
document.write(variable + "<br/>");
}
var str1 = "Comeonforyou!";
document.write("字符串长度是:" + str1.length + "<br/>");
document.write("小写:" + str1.toLowerCase() + "<br/>");
document.write("大写:" + str1.toUpperCase() + "<br/>");
document.write("第1个字符是:" + str1.charAt(0) + "<br/>");
document.write("第5个字符是:" + str1.charAt(6) + "<br/>");
var str2 = str1.substring(2, 5);
document.write(str2 + "<br/>");
var str = "I am iron man,don't forget it,over.";
document.write(str.replace("am", "hero" + "<br/>"));
document.write(str.replace(/iron/g, "hero" + "<br/>"));
var str = "I get it";
var arr1 = str.split(" ");//有空格
document.write("数组第1个元素是:" + arr1[0] + "<br/>");
document.write("数组第2个元素是:" + arr1[1] + "<br/>");
document.write("数组第3个元素是:" + arr1[2] + "<br/>");
var arr2 = str.split("");//无空格
document.write("数组第1个元素是:" + arr2[0] + "<br/>");
document.write("数组第2个元素是:" + arr2[1] + "<br/>");
document.write("数组第3个元素是:" + arr2[2] + "<br/>");
document.write("数组第4个元素是:" + arr2[3] + "<br/>");
var str = "The world jojo!";
document.write(str.indexOf("hh") + "<br/>");
document.write(str.indexOf("world") + "<br/>");
document.write(str.indexOf("jojo") + "<br/>");
document.write("e首次出现的下标是:" + str.indexOf("e") + "<br/>");
document.write("e最后出现的下标是:" + str.lastIndexOf("e") + "<br/>");
var str = "Can you can a can as a Canner can can a can";
function countChar(str, char) {
var charCount = 0;
for (var i = 0; i < str.length; i++) {
var char = str.charAt(i);
//将每一个字符转换为小写,然后判断是否与“c”相等
if (char.toLowerCase() == "c") {
charCount += 1;
}
}
return charCount;
}
writeDocument("There are " + countChar(str, "c") + " c in " + str);
//统计字符串中有多少个数字?
function getNum(str) {
var num = 0;
for (var i = 0; i < str.length; i++) {
var char = str.charAt(i);
//isNaN()对空格字符会转化为0,需要加个判断charAt(i)不能为空格
if (char != " " && !isNaN(char)) {
num++;
}
}
return num;
}
document.write(getNum("12gfc5d"));
console