String类型

本文详细介绍了JavaScript中常用的字符串操作方法,包括去除空格、大小写转换、字符串拼接、截取、查找替换等操作,并提供了具体的使用示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

trim( )方法 删除前置及后缀的所有空格 然后返回结果。
var stringValue='     hello world      ';
alert(stringValue.trim());   // hello world

trimLeft( ) 删除字符串开头空格            trimRight( ) 删除字符串末尾空格

字符串大小写转换方法

  ECMAScript中涉及大小写转换的方法有4个:toLowerCase( ), toLocaleLowerCase( ),toUpperCase( )和 toLocaleUpperCase( )。

var stringValue = 'hello world';
alert(stringValue.toLocaleUpperCase()); //HELLO WORLD
alert(stringValue.toUpperCase());  //HELLO WORLD
alert(stringValue.toLocaleLowerCase()); //hello world
alert(stringValue.toLowerCase());//hello world

字符串操作方法

concat( )方法。用于讲一个或多个字符串拼接起来,返回拼接得到的新字符串。

var stringValue='hello';
var result = stringValue.concat('world');
alert(result);   //helloworld
alert(stringValue);  //hello

slice( ) substr( ) substring( )

var stringValue='hello world';
  alert(stringValue.slice(3));       //lo world
  alert(stringValue.substring(3));   //lo world
  alert(stringValue.substr(3));      //lo world
  alert(stringValue.slice(3,7));     //lo w
  alert(stringValue.substring(3,7));  //lo w
  alert(stringValue.substr(3,7));    //lo worl
alert(stringValue.slice(-3));       //rld
alert(stringValue.substring(-3));   //hello world
alert(stringValue.substr(-3));      //rld
alert(stringValue.slice(3,-4));     //lo w
alert(stringValue.substring(3,-4));  //hel
alert(stringValue.substr(3,-4));    //  ''

  字符串位置方法

indexOf( )  lastIndexOf( )

    var stringValue='hello world';
    alert(stringValue.indexOf('o'));    //4
    alert(stringValue.lastIndexOf('o')); //7
  alert(stringValue.indexOf('o',6));    //7    第二个参数是从第几个位置开始搜索。
  alert(stringValue.lastIndexOf('o',6)); //4

   replace( )

var text = 'cat,bat,sat,fat';
var result = text.replace('at','ond');
alert(result);  //cond,bat,sat,fat  // 替换字符串'at'第一次出现的位置。
result= text.replace(/at/g,'ond');
alert(result);    //cond,bond,sond,fond  // 通过带有全局标记的正则表达式,将全的'at'替换为'ond'

 split( )方法可以基于指定的分隔符将一个字符串分割成多个子字符串,并将其放到一个数组中。

var colors = "red,blue,red,purple,orange";
console.log(colors.split(","));  //["red", "blue", "red", "purple", "orange"]
console.log(colors.split(",",2));  //["red", "blue"]  第二个参数指定数组的大小。













评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值