JavaScript 字符串处理常用方法详解

作者:闭包旅人时间:2026-10-25 15:02:00浏览:86

本文总结了 JavaScript 中常用的字符串处理方法,包括使用 length 属性计算字符串长度、利用 indexOf() 定位字符首次出现位置、通过 match() 查找特定字符串以及使用 replace() 进行字符替换。

1.计算字符串的长度

计算字符串长度

代码如下:

 
var txt="Hello World!"
document.write(txt.length)

2.indexOf() 方法

使用 indexOf 定位字符

介绍如何使用 indexOf() 方法定位字符串中指定字符首次出现的位置。


代码如下:

 
<script type="text/javascript">
var str="Hello world!" //w小写
document.write(str.indexOf("H") + "<br />") //0
document.write(str.indexOf("World") + "<br />") //-1
document.write(str.indexOf("world")) //6
</script>

3.match() 方法

使用 match 查找字符串

查找字符串中特定的字符,如果找到则返回该字符串。


代码如下:

 
<script type="text/javascript">
var str="Hello world!"
document.write(str.match("world") + "<br />") //world
document.write(str.match("World") + "<br />") //null
document.write(str.match("worlld") + "<br />") //null
document.write(str.match("world!")) //world!
</script>

4.如何替换字符串中的字符 - replace()

使用 replace 替换字符

使用 replace() 方法在字符串中用某些字符替换另一些字符。


代码如下:

 
<script type="text/javascript">
var str="Visit cnblogs.com!"
document.write(str.replace(/cnblogs.com/,"Mamogu.com"))
</script>
作者最新文章