84-----JS基础-----字符串的方法

一 代码

不难,用到时看一下即可。

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script type="text/javascript">
			//创建一个字符串
			var str = "Hello Atguigu";
			
			/*
			 * 在底层字符串是以字符数组的形式保存的
			 * ["H","e","l"]
			 */
			
			/*
			 * 1. length属性
			 * 	- 可以用来获取字符串的长度
			 */
			//console.log(str.length);
			//console.log(str[5]);
			
			/*
			 * 2. charAt()
			 * 	- 可以返回字符串中指定位置的字符,不会改变原数组
			 * 	- 根据索引获取指定的字符
			 */
			str = "中Hello Atguigu";
			
			var result = str.charAt(6);
			
			/*
			 * 3. charCodeAt()
			 * 	- 获取指定位置字符的字符编码(Unicode编码)
			 */
			
			result = str.charCodeAt(0);
			
			/*
			 * 4. String.formCharCode()
			 * 	- 可以根据字符编码去获取字符
			 */
			result = String.fromCharCode(0x2692);
			
			/*
			 * 5. concat()
			 * 	- 可以用来连接两个或多个字符串,它不会改变原数组
			 * 	- 作用和+一样
			 */
			result = str.concat("你好","再见");
			
			/*
			 * 6. indexof()
			 * 	- 该方法可以检索一个字符串中是否含有指定内容
			 * 	- 如果字符串中含有该内容,则会返回其第一次出现的索引
			 * 		如果没有找到指定的内容,则返回-1
			 * 	- 可以指定一个第二个参数,指定开始查找的位置
			 * 
			 * 7. lastIndexOf();
			 * 	- 该方法的用法和indexOf()一样,
			 * 		不同的是indexOf是从前往后找,
			 * 		而lastIndexOf是从后往前找
			 * 	- 也可以指定开始查找的位置
			 */
			
			str = "hello hatguigu";
			
			result = str.indexOf("h",1);
			
			result = str.lastIndexOf("h",5);
			
			/*
			 * 8. slice()
			 * 	- 可以从字符串中截取指定的内容
			 * 	- 不会影响原字符串,而是将截取到内容返回
			 * 	- 参数:
			 * 		第一个,开始位置的索引(包括开始位置)
			 * 		第二个,结束位置的索引(不包括结束位置)
			 * 			- 如果省略第二个参数,则会截取到后边所有的
			 * 		- 也可以传递一个负数作为参数,负数的话将会从后边计算
			 */
			str = "abcdefghijk";
			
			result = str.slice(1,4);
			result = str.slice(1,-1);
			
			/*
			 * 9. substring()
			 * 	- 可以用来截取一个字符串,可以slice()类似
			 * 	- 参数:
			 * 		- 第一个:开始截取位置的索引(包括开始位置)
			 * 		- 第二个:结束位置的索引(不包括结束位置)
			 * 		- 不同的是这个方法不能接受负值作为参数,
			 * 			如果传递了一个负值,则默认使用0
			 * 		- 而且他还自动调整参数的位置,如果第二个参数小于第一个,则自动交换
			 */
			
			result = str.substring(0,1);
			
			/*
			 * 10. substr()
			 * 	- 用来截取字符串
			 * 	- 参数:
			 * 		1.截取开始位置的索引
			 * 		2.截取的长度
			 */
			
			str = "abcdefg";
			result = str.substr(3,2);
			
			/*
			 * 11. split()
			 * 	- 可以将一个字符串拆分为一个数组
			 * 	- 参数:
			 * 		-需要一个字符串作为参数,将会根据该字符串去拆分数组
             *  - 如果传递一个空串作为参数,则会将每个字符都拆分为数组中的一个元素。
			 */
			str = "abcbcdefghij";
			result = str.split("d");
			result = str.split("");
			
			//console.log(Array.isArray(result));
			//console.log(result[0]);
			console.log(result);
			
			
			str = "abcdefg";
			/*
			 * 12. toUpperCase()
			 * 	- 将一个字符串转换为大写并返回
			 */
			result = str.toUpperCase();
			
			str = "ABCDEFG";
			
			/*
			 * 13. toLowerCase()
			 * 	-将一个字符串转换为小写并返回
			 */
			result = str.toLowerCase();
			//console.log(result);
			
			
		</script>
	</head>
	<body>
	</body>
</html>

Guess you like

Origin blog.csdn.net/weixin_44517656/article/details/121399499