常用JS字符串方法

String 对象

String 对象用于处理文本(字符串)。

字符串创建

首先介绍一下字符串的创建方法,有两种方式:
字面量方式:

	var txt = "string";

构造函数方式:

	var txt = new String("string");

字符串方法

方法描述
charAt()返回在指定位置的字符。
charCodeAt()返回在指定的位置的字符的 Unicode 编码。
concat()连接字符串。
fromCharCode()从字符编码创建一个字符串。
indexOf()检索字符串。
lastIndexOf()从后向前搜索字符串。
match()找到一个或多个正则表达式的匹配。
replace()替换与正则表达式匹配的子串。
search()检索与正则表达式相匹配的值。
slice()提取字符串的片断,并在新的字符串中返回被提取的部分。
split()把字符串分割为字符串数组。
substr()从起始索引号提取字符串中指定数目的字符。
substring()提取字符串中两个指定的索引号之间的字符。
toLowerCase()把字符串转换为小写。
toUpperCase()把字符串转换为大写。
toString()返回字符串。
valueOf()返回某个字符串对象的原始值。
charAt()

返回在指定位置的字符。

var str="hello"
console.log(str.charAt(0))//h
charCodeAt()

返回在指定的位置的字符的 Unicode 编码。

var str="hello"
 console.log(str.charCodeAt(1))//101
concat()

连接字符串。

var a = "hello";  
 var b = "world";  
 var c = a.concat(b);
 console.log(c);//helloworld
fromCharCode()

从字符编码创建一个字符串。

console.log(String.fromCharCode(65,66,67))//ABC
indexOf()

检索字符串。

var str="Hello world!"
console.log(str.indexOf("Hello"))//0
console.log(str.indexOf("hello"))//-1
console.log(str.indexOf("world"))///6
lastIndexOf()

从后向前搜索字符串。

var str="I am from runoob,welcome to runoob site.";
var n=str.lastIndexOf("runoob");
console.log(n);//28
match()

找到一个或多个正则表达式的匹配。

var str="1 abc 2 def 3"
console.log(str.match(/\d+/g))//123
replace()

替换与正则表达式匹配的子串。

var str="abc Def!"
console.log(str.replace(/abc/, "CBA"))//CBA Def!
search()

检索与正则表达式相匹配的值。

var str="abc DEF!"
console.log(str.search(/DEF/))//4
slice()

提取字符串的片断,并在新的字符串中返回被提取的部分。

var str="abc def ghk"
console.log(str.slice(6))//f ghk
split()

把字符串分割为字符串数组。

var str="abc def ghi jkl"    
console.log(str.split(" "))//["abc", "def", "ghi", "jkl"]
console.log(str.split("") )//["a", "b", "c", " ", "d", "e", "f", " ", "g", "h", "i", " ", "j", "k", "l"]
console.log(str.split(" ",3))//["abc", "def", "ghi"]
substr()

从起始索引号提取字符串中指定数目的字符。

var str="abc def"
console.log(str.substr(2))//c def
console.log(str.substr(2,4))// c de 
substring()

提取字符串中两个指定的索引号之间的字符。

var str="abc def"
console.log(str.substring(2))//c def
console.log(str.substring(2,4))// c 
toLowerCase()

把字符串转换为小写。

var str="ABC def!"
console.log(str.toLowerCase())//abc def!
toUpperCase()

把字符串转换为大写。

var str="ABC def!"
console.log(str.toUpperCase())//ABC DEF!
toString()

返回字符串。

var n = 1234;
console.log(typeof n.toString);//String
valueOf()

返回某个字符串对象的原始值。

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值