JavaScript String对象
string对象
String 对象用于处理文本(字符串)。
字符串常用方法
charAt()
返回在指定位置的字符
<script>
let str="hello word!";
document.write("<h2>:"+str.charAt(4)+"</h2>")
</script>
charCodeAt()
返回在指定位置的字符编码
<script>
let str="hello word!";
document.write("<h2>:"+str.charCodeAt(4)+"</h2>")
</script>
concat()
连接字符串
<script>
let str="hello word!";
let str2=str.concat("你好","世界","啊啊啊");
</script>
fromCharCode()
转换字符编码
<script>
let str="hello word!";
document.write("<h2>:"+string.fromCharCode()+"</h2>")
</script>
indexOf()
检索字符串
<script>
let str="hello word!";
document.write("<h2>:"+str2.indexOf("你好",6)+"</h2>");
</script>
lastIndexOf()
从后向前检索
<script>
let str="hello word!";
document.write("<h2>:"+str.lastIndexOf('o')+"</h2>");
</script>
localeCompare()
用特定的顺序来比较两个字符串
<script>
let str="hello word!";
let str3="张三".localeCompare("张四");
document.write("<h2>张三李四比较的结果:"+str3+"</h2>");
let strs=["张三","李四","王五","赵六","神奇","樱桃"];
for(let i=0;i<strs.length-1;i++){
for(let j=0;j<strs.length-1-i;j++){
if(strs[j].localeCompare(strs[j+1])){
let temp=strs[j];
strs[j]=strs[j+1];
strs[j+1]=temp;
}
}
}
document.write("<h2>排序:"+strs+"</h2>");
</script>
replace()
替换
<script>
let str="hello word!";
document.write("<h2>:"+str2.replace("世界","丫丫")+"</h2>");
</script>
split()
分割字符串
<script>
let str="hello word!";
document.write("<h2>:"+str2.split("")+"</h2>");
</script>
substr()
提取字符串
<script>
let str="hello word!";
document.write("<h2>:"+str2.substr(3,7)+"</h2>");
</script>
substring()
提取字符串中两个指定的索引之间的字符
<script>
let str="hello word!";
document.write("<h2>:"+str2.substring()+"</h2>");
</script>
toLocaleLowerCase()
转小写
<script>
let str="hello word!";
document.write("<h2>:"+"壹ABCD".toLocaleLowerCase()+" </h2>");
</script>
toUpperCase()
转大写
<script>
let str="hello word!";
document.write("<h2>:"+"壹Abcd".toUpperCase()+"</h2>");
</script>
valueOf()
原始值
<script>
let str="hello word!";
document.write("<h2>:"+str2.valueOf()+"</h2>");
</script>