一、数组查找:indexOf(): lastIndexOf() includes():true/false
- indexOf():可返回某个指定的字符串值在字符串中首次出现的位置。
如果没有找到匹配的字符串则返回 -1。
注意: indexOf() 方法区分大小写。
<body> <p id="demo">单击按钮来定位指定文本首次出现的位置。</p> <button onclick="myFunction()">点我</button> <script> function myFunction(){ var str="Hello world, welcome to the universe."; var n=str.indexOf("welcome"); document.getElementById("demo").innerHTML=n; } </script> </body>
菜鸟教程演示:https://www.runoob.com/try/try.php?filename=tryjsref_indexof
- lastIndexOf() :可返回一个指定的字符串值最后出现的位置,如果指定第二个参数 start,则在一个字符串中的指定位置从后向前搜索。
注意: 该方法将从后向前检索字符串,但返回是从起始位置 (0) 开始计算子字符串最后出现的位置。 看它是否含有字符串。
开始检索的位置在字符串的 start 处或字符串的结尾(没有指定 start 时)。
如果没有找到匹配字符串则返回 -1 。
注意:lastIndexOf() 方法是区分大小写的!
<body> <p id="demo">单击按钮显示指定值最后一次出现的位置。</p> <button onclick="myFunction()">点我</button> <script> function myFunction(){ var str="I am from runoob,welcome to runoob site."; var n=str.lastIndexOf("runoob"); document.getElementById("demo").innerHTML=n; } </script> </body>
菜鸟教程演示:https://www.runoob.com/try/try.php?filename=tryjsref_lastindexof
- includes():用于判断字符串是否包含指定的子字符串。
如果找到匹配的字符串则返回 true,否则返回 false。
<body> <p>点击按钮查看检测结果。</p> <button onclick="myFunction()">点我</button> <p id="demo"></p> <p><strong>注意:</strong> IE 11 及更早版本不支持 includes() 方法 。</p> <script> function myFunction() { var str = "Hello world, welcome to the Runoob."; var n = str.includes("world"); document.getElementById("demo").innerHTML = n; } </script> </body>
菜鸟教程演示:https://www.runoob.com/try/try.php?filename=tryjsref_string_includes
二、数组转字符串:String() toString() join()
- String() :把对象的值转换为字符串。
<script> var test1= new Boolean(1); var test2= new Boolean(0); var test3= new Boolean(true); var test4= new Boolean(false); var test5= new Date(); var test6= new String("999 888"); var test7=12345; document.write(String(test1)+ "<br>");// true document.write(String(test2)+ "<br>");// false document.write(String(test3)+ "<br>");// true document.write(String(test4)+ "<br>");// false document.write(String(test5)+ "<br>");// Thu Aug 05 2021 20:51:54 GMT+0800 (中国标准时间) document.write(String(test6)+ "<br>");// 999 888 document.write(String(test7)+ "<br>");// 12345 </script>
- toString() :把数字转换为字符串
<body> <p id="demo">单击按钮来显示格式化的数字</p> <button onclick="myFunction()">点我</button> <script> function myFunction(){ var num = 15; var x = document.getElementById("demo"); x.innerHTML=num.toString();// 15 } </script> </body>
- join():用于把数组中的所有元素转换一个字符串。
<body> <p id="demo">点击按钮将数组作为字符串输出。</p> <button onclick="myFunction()">点我</button> <script> function myFunction(){ var fruits = ["Banana", "Orange", "Apple", "Mango"]; var x=document.getElementById("demo"); x.innerHTML=fruits.join();// Banana,Orange,Apple,Mango } </script> </body>