substring()是在JavaScript一个内置函数,其被用于从字符串中获取子字符串,本篇文章我们就来详细看看substring的用法。 
我们先来看一下substring的基本语法 string.substring(indexA, [indexB]) indexA - 0到1之间的整数,小于字符串的长度。 indexB(可选) - 0到字符串长度之间的整数。 substring方法根据给定的参数返回新的子字符串。 我们来看具体的示例 代码如下 <!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
// 将字符串作为变量
var string = "sghxdysgcghd";
a = string.substring(0, 4)
b = string.substring(1, 6)
c = string.substring(5)
d = string.substring(0)
// 输出新的字符串
// 给定字符串的一部分
document.write(a + "<br>");
document.write(b + "<br>");
document.write(c + "<br>");
document.write(d + "<br>");
</script>
</body>
</html> 浏览器上显示效果如下:

索引始终以0开头。如果我们仍然把索引取为负数,它将被认为是零,并且索引不能是小数,如果它是小数,它将被转换成比其小的整数。 我们来看示例 代码如下 <!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script>
var string = "sghxdysgcghd";
a = string.substring(-1)
b = string.substring(2.5)
c = string.substring(2.9)
document.write(a + "<br>");
document.write(b + "<br>");
document.write(c + "<br>");
</script>
</body>
</html> 浏览器上显示效果如下 
本篇文章到这里就全部结束了,更多精彩内容大家可以关注模板之家(www.mb5.com.cn)的其他相关栏目教程!!! 以上就是substring方法怎么使用的详细内容,更多请关注模板之家(www.mb5.com.cn)其它相关文章! |