JavaScript string方法

avaScript 字符串(String) 对象


String 对象用于处理已有的字符块。


JavaScript 字符串

一个字符串用于存储一系列字符就像 "John Doe".

一个字符串可以使用单引号或双引号:

实例

var carname="Volvo XC60";
var carname='Volvo XC60';

你使用位置(索引)可以访问字符串中任何的字符:

实例

var character=carname[7];

字符串的索引从零开始, 所以字符串第一字符为 [0],第二个字符为 [1], 等等。

你可以在字符串中使用引号,如下实例:

实例

var answer="It's alright";
var answer="He is called 'Johnny'";
var answer='He is called "Johnny"';

或者你可以在字符串中使用转义字符(\)使用引号:

实例

var answer='It\'s alright';
var answer="He is called \"Johnny\"";


 


字符串(String)

字符串(String)使用长度属性length来计算字符串的长度:

实例

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

var txt="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
document.write(txt.length);



在字符串中查找字符串

字符串使用 indexOf() 来定位字符串中某一个指定的字符首次出现的位置:

实例

var str="Hello world, welcome to the universe.";
var n=str.indexOf("welcome");


如果没找到对应的字符函数返回-1

lastIndexOf() 方法在字符串末尾开始查找字符串出现的位置。


内容匹配

match()函数用来查找字符串中特定的字符,并且如果找到的话,则返回这个字符。

实例

var str="Hello world!";
document.write(str.match("world") + "<br>");
document.write(str.match("World") + "<br>");
document.write(str.match("world!"));


 


替换内容

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

实例

str="Please visit Microsoft!"
var n=str.replace("Microsoft","Runoob");

 


字符串大小写转换

字符串大小写转换使用函数 toUpperCase() / toLowerCase():

实例

var txt="Hello World!";       // String
var txt1=txt.toUpperCase();   // txt1 文本会转换为大写
var txt2=txt.toLowerCase();   // txt2 文本会转换为小写

 


字符串转为数组

字符串使用split()函数转为数组:

实例

txt="a,b,c,d,e"   // String
txt.split(",");   // 使用逗号分隔
txt.split(" ");   // 使用空格分隔
复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="con">
    <h3 id="title" onclick="change()">标题</h3>
</div>
    <script>

        //js内置String对象

        var str = "abcdef";
        //字符串长度是length属性
        alert(str.length);//输出结果 6
        //charAt 传递索引,返回字符
        alert(str.charAt(3));//输出结果 d
        //传递字符串,返回第一次出现的索引,找不到返回-1
        alert(str.indexOf("c"));//输出结果 2
        //substring 截取字符串包含开始索引,不包含结束索引
        alert(str.substring(1,4));//输出结果 bcd
        //substr 截取字符串,包含开始索引,后面的参数是要几个
        alert(str.substr(1,4));//输出结果 bcde
        
        
    </script>
</body>
</html>
复制代码

 


txt.split("|");   // 使用竖线分隔 
 
 
posted @   权。  阅读(66)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示