JS_字符串操作
Posted 手可摘星辰。
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JS_字符串操作相关的知识,希望对你有一定的参考价值。
<script> var str = \'hello world\' // 获取字符串的长度 console.log(str.length) // 获取下标为1的字符 console.log(str.charAt(1)) // 获取下标为1的字符的对应的编码 console.log(str.charCodeAt(1)) // 将wdc和yhf拼接在字符串的后面 console.log(str.concat(\'wdc\',\'yhf\')) </script>
结果:
<script> var str = \'hello world\' // 从前往后查找字符‘o’ console.log(str.indexOf(\'o\')) // 从后往前查找字符‘o’ console.log(str.lastIndexOf(\'o\')) // 从下标6往后查找字符‘o’ console.log(str.indexOf(\'o\',6)) // 从下标6往前查找字符‘o’ console.log(str.lastIndexOf(\'o\',6)) var wdc = \' hollo world \' console.log(wdc) // 清除字符串前后的空格 console.log(wdc.trim()) var yhf = \'Hello Wdc\' // 转换为小写字母 console.log(yhf.toLowerCase()) // 转换为大写字母 console.log(yhf.toUpperCase()) </script>
结果;
应用:查找当前字符串中的所有位置
<script> var str = \'Blog garden was founded in January 2004, blog garden was born in yangzhou, jiangsu province, such a very backward IT small city, although the city is small, but there are a lot of innovative people, blog garden was born for such a simple reason.\' var arr = [] var pos = str.indexOf(\'o\') while(pos > -1){ arr.push(pos) pos = str.indexOf(\'o\', pos + 1) } console.log(arr) </script>
结果:
以上是关于JS_字符串操作的主要内容,如果未能解决你的问题,请参考以下文章