String 字符串对象参考文档 : https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String
concat 函数 的作用是 拼接字符串 , 将 若干 字符串 参数 连接到 调用 concat 函数的字符串 后面 , 并返回一个新的字符串 ;
字符串是不可变的 , 调用 concat 函数不会改变调用者字符串 , 返回的字符串是新创建的字符串 ;
concat 函数语法如下 :
concat(str1)
concat(str1, str2)
concat(str1, str2, /* …, */ strN)
参考文档 : https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/concat
代码示例 :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<!-- 设置 meta 视口标签 -->
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no,maximum-scale=1.0,minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>JavaScript</title>
<style></style>
<script>
// 给定一个字符串
var str = 'Hello';
// 拼接字符串
console.log(str.concat(' World'));
</script>
</head>
<body>
</body>
</html>
执行结果 :
substr 函数 可以获取字符串的一部分子字符串 , 截取从指定的索引开始的指定个数的字符串 ;
该操作不会改变调用该函数的字符串 , 返回的结果是一个新字符串 ;
substr 函数原型如下 :
substr(start)
substr(start, length)
参考文档 : https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/substr
该函数 已经不推荐使用 , 官方文档中推荐使用 substring 函数 和 slice 函数 ;
代码示例 :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<!-- 设置 meta 视口标签 -->
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no,maximum-scale=1.0,minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>JavaScript</title>
<style></style>
<script>
// 给定一个字符串
var str = 'Hello';
// 拼接字符串
console.log(str.concat(' World'));
// 截取字符串
console.log(str.substr(2, 2));
</script>
</head>
<body>
</body>
</html>
执行结果 :
substring 函数 可以截取 从 指定索引位置开始 ( 包括该索引 ) 到 指定索引位置结束 ( 不包括该索引 ) 的 子字符串 ;
substring 函数原型如下 :
substring(indexStart)
substring(indexStart, indexEnd)
参考文档 : https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/substring
代码示例 :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<!-- 设置 meta 视口标签 -->
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no,maximum-scale=1.0,minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>JavaScript</title>
<style></style>
<script>
// 给定一个字符串
var str = 'Hello';
// 拼接字符串
console.log(str.concat(' World'));
// 截取字符串
console.log(str.substr(2, 2));
// 截取字符串
console.log(str.substring(2, 4));
</script>
</head>
<body>
</body>
</html>
执行结果 :