字符串其他的属性和方法
属性:
- length
- prototype
- constructor
方法:
- charAt()
- charCodeAt()
- concat()
- fromCharCode()
- indexOf()
- lastIndexOf()
- match()
- replace()
- search()
- slice()
- split()
- substr()
- substring()
- toLowerCase()
- toUpperCase()
- valueOf()
1.使用length属性可以计算字符串长度
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>javascript</title>
</head>
<body>
<script>
var txt1 = "Hello World!";
document.write("<p>" + txt1.length + "</p>");
var txt2="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
document.write("<p>" + txt2.length + "</p>");
</script>
</body>
</html>
2.用indexOf属性查找某一个指定字符首先出现的位置
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>javascript</title>
</head>
<body>
<p id="p1">Click the button to locate where "locate" first occurs.</p>
<p id="p2"></p>
<button οnclick="myFunction()">点我</button>
<script>
function myFunction(){
var str=document.getElementById("p1").innerHTML;
var n=str.indexOf("locate");
document.getElementById("p2").innerHTML=n+1;//这里加一的原因是从零开始计数的
}
</script>
</body>
</html>
3.使用match()函数用来查找字符串中特定的字符,并且如果找到的话,则返回这个字符。找不到的话返回null
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>javascript</title>
</head>
<body>
<script>
var str="Hello world!";
document.write(str.match("world") + "<br>");
document.write(str.match("World") + "<br>");
document.write(str.match("world!"));
</script>
</body>
</html>
4.使用repla(“目标”“替代值”)的函数去替代特定的目标。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript</title>
</head>
<body>
<p>替换 "Microsoft" 为 "Runoob" :</p>
<p id="demo">请访问 Microsoft!</p>
<button οnclick="myFunction()">点我</button>
<script>
function myFunction() {
var str = document.getElementById("demo").innerHTML;
var txt = str.replace("Microsoft","Runoob");
document.getElementById("demo").innerHTML = txt;
}
</script>
</body>
</html>
属性:
方法: