JavaScript 入门教程

JavaScript是一门Web编程语言,用来实现网页的交互功能,它和HTML、CSS共同组成了个Web开发的基础工具集合,也是前端开发者必备的技能;学习JavaScript教程可以了解它在网页开发中的所有特性和相关概念,让我们能够更加快速的去开发Web应用。

W3CAPI
1
2025-07-04 06:54:18
文档目录
我的书签
 

substring

JavaScript substring 方法:字符串对象

详细说明

这个substring()方法,用于从指定字符串中提取两个给定索引之间的部分内容。

版本实现

实现于JavaScript 1.0

语法说明

substring(ind1, ind2)
执行一下

代码说明

ind1、ind2:介于0到字符串长度减1之间的整数。
注意:substring() 从 ind1 开始提取字符直至 ind2(不包含 ind2)。

  • 若ind1小于0则自动将其设为0。
  • 若ind2大于字符串长度,则其自动被设置为该字符串的长度。
  • 若ind1等于ind2,该函数返回空字符串。
  • 如未指定ind2,ind1将提取字符至字符串结尾。

示例:

以下网页文档演示了substring()方法支持的多种使用方式。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<title>JavaScript String object - substring() method example</title>
</head>
<body>
<h1 style="color: red">JavaScript String object : substring() method</h1>
<hr />
<script type="text/javascript">
//This is done to make the following JavaScript code compatible to XHTML. <![CDATA[
var str="Javascript"
document.write(str.substring(0,3)+"<br>")
document.write(str.substring(4,7)+"<br>")
document.write(str.substring(7,4)+"<br>")
document.write(str.substring(0,10))
//]]>
</script>
</body>
</html>

执行一下

在浏览器中查看示例

支持的浏览器

IE浏览器7火狐3.6谷歌Chrome 7Safari 5.0.1 版Opera 10
YesYesYesYesYes

另请参阅:

JavaScript 核心对象、方法及属性。

上一篇:JavaScript substr() 方法:字符串对象
下一篇:JavaScript sup()方法:字符串对象

友情提示