String

一 概念

#### 1、常用字符串

```js
'string' | "string" | 'my name is "zero"' | "I'm boy" | "I \"love\" you"
```

#### 2、常用属性

```js
length:字符串长度
```

#### 3、常用方法

```js
charAt(n):指定索引字符,同[n]
concat(str):将目标字符串拼接到指定字符串之后
indexOf(str):指定字符串第一次出现的位置
lastIndexOf(str):指定字符串最一次出现的位置
replace(re, str):将正则匹配到的字符串替换为指定字符串
substr(n, m):从索引n开始,截取m个字符长度(m省略代表截取到最后)
substring(n, m):从索引n开始,截取到索引m(m省略代表截取到最后)
slice(n, m):同substring(n, m)
split(re):以指定正则将字符串拆分为数组
toUpperCase():转换为大写
toLowerCase():转换为小写
trim():去除首尾空白字符
```

二 代码示范

<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>String</title>
</head>
<body>
String
</body>
<script type="text/javascript">
// '' | "" | "''" | '""' | "\"\"" | '\'\''
var str = '字符串';
console.log(str);

// length
console.log(str.length);

// 方法
str = "abc123hello123GOOD123嘿嘿";
// 自定索引下的字符
console.log(str.charAt(1));
console.log(str[1]);
// 拼接,返回拼接后的字符串
var newStr = str.concat(123);
console.log(str,'\n', newStr);

// indexOf(str):指定字符串第一次出现的位置
console.log(str.indexOf("123")); // 3

// replace(re, str):将正则匹配到的字符串替换为指定字符串
newStr = str.replace("hello", "world");
console.log(str, newStr);

// substr(n, m):从索引n开始,截取m个字符长度(m省略代表截取到最后)
// 索引3开始,截取3个字符长度
newStr = str.substr(3, 3);
console.log(newStr);

// slice(n, m):同substring(n, m)
// 索引3开始,6结束(不包含6) [3, 6)
newStr = str.slice(3, 6);
console.log(newStr);

// split(re, n):以指定正则将字符串拆分为数组, n可选为截取后得到的数组最大长度
var arr = str.split("123", 2);
console.log(arr);

// trim():去除首尾空白字符
str = " 123 abc "
console.log(str.trim());
</script>
</html>

posted @ 2018-10-17 17:45  不沉之月  阅读(53)  评论(0编辑  收藏  举报