javascript 字符串
字符串使用转义字符
<script>
var name = "\"zlx is a student \"";
document.write(name + "<br>");
</script>
获取字符位置indexOf()
<p id="one">zlx is a student</p>
<p id="two">0</p>
<button onclick="myFunction()">点击</button>
<script>
function myFunction() {
var str = document.getElementById("one").innerHTML;
var n = str.indexOf("student");
document.getElementById("two").innerHTML = n + 1;
}
</script>
如果没找到对应的字符函数返回-1
内容匹配match()
<body>
<p id="one">zlx is a student</p>
<script>
var str = document.getElementsByTagName('p')[0].innerHTML;
document.write(str.match("a"));
</script>
</body>
内容替换replace()
<body>
<p>zlx is a student</p>
<button onclick="myfunction()">点击</button>
<script>
function myfunction() {
var str = document.querySelector('p').innerHTML;
var text = str.replace("zlx", "zyx");
document.querySelector('p').innerHTML = text;
}
</script>
</body>
字符串转数组split()
<body>
<p>zhong li xi</p>
<button onclick="myfunction()">显示数组</button>
<script>
function myfunction() {
var str = document.querySelector('p').innerHTML;
var arry = str.split(" ");
document.querySelector("p").innerHTML = arry[2];
}
</script>
</body>
大小写转换toUpperCase() / toLowerCase():
<body>
<p>zlx</p>
<button onclick="myfunction()">点我换大写</button>
<script>
function myfunction() {
var name = document.querySelector('p').innerHTML;
var Name = name.toUpperCase();
document.querySelector('p').innerHTML = Name;
}
</script>
</body>
本文介绍了JavaScript中字符串的基本操作,包括使用转义字符展示特殊字符,利用indexOf()查找字符位置,match()进行内容匹配,replace()实现内容替换,以及split()将字符串转换为数组。此外,还展示了toUpperCase()和toLowerCase()用于大小写转换的实例,这些是JavaScript字符串处理的重要方法。

被折叠的 条评论
为什么被折叠?



