0
点赞
收藏
分享

微信扫一扫

JS技术(5)---String常用函数(slice,substr,substring)运用


说明
String 对象的方法 slice()、substring() 和 substr() (不建议使用)都可返回字符串的指定部分。slice() 比 substring() 要灵活一些,因为它允许使用负数作为参数。slice() 与 substr() 有所不同,因为它用两个字符的位置来指定子串,而 substr() 则用字符位置和长度来指定子串。
还要注意的是,String.slice() 与 Array.slice() 相似。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<div id="demo">Tom is a lady-killer,jeneter is really turned me on</div>
</head>
<body>
<script type="application/javascript">
//var txt = document.getElementById("demo").value();
var txt = "this is a nice day !"
//替换
document.write(txt.replace(/nice/, "good")+"<br/>");
//索引位置
document.write(txt.indexOf("nice")+"<br/>");
//是否匹配
document.write(txt.match("day")+"<br/>");
//substr() 则用字符位置和长度来指定子串。负数表示从后面开始数
document.write("substr==" + txt.substr(-6, 16)+"<br/>");
//substring() 则用字符位置和结束位置来指定子串,不允许负数。
document.write("substring==" + txt.substring(1, 6)+"<br/>");
//substring() 则用字符位置和结束位置来指定子串,允许负数。
document.write("slice==" + txt.slice(-6, -1)+"<br/>");
</script>
</body>
</html>

举报

相关推荐

0 条评论