Javascript 字符串

JavaScript 字符串 您能够使用单引号或双引号

1、创建字符串

  • 字符串 您能够使用单引号或双引号 var str = ''
  • 字符串对象 var firstName = new String("Bill")

2、特殊字符

转义字符, 在字符前面加上反斜杠 \

3、字符串长度 内建属性 length 可返回字符串的长度:

var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length;

4、查找字符串中的字符串 indexOf() 方法返回字符串中指定文本首次出现的索引 如果未找到文本, indexOf() 均返回 -1

5、lastIndexOf() 方法返回指定文本在字符串中最后一次出现的索引 如果未找到文本, lastIndexOf() 均返回 -1

两种方法都接受作为检索起始位置的第二个参数。

var str = "The full name of China is the People's Republic of China.";
var pos = str.indexOf("China");

6、检索字符串中的字符串 search() 方法搜索特定值的字符串,并返回匹配的位置

indexOf() 与 search(),是相等的 , 不同的地方在于 search()没有第二个参数

var str = "The full name of China is the People's Republic of China.";
var pos = str.search("locate");

7、提取字符串的某个部分并在新字符串中返回被提取的部分。 slice(str1,str2) 方法 可以传递两个参数 str1起始索引(开始位置),str2终止索引(结束位置), 如果不传参数则返回 拷贝的字符串

var str = "Apple, Banana, Mango";
var res = str.slice(); //"Apple, Banana, Mango"

8、substring() 方法

substring() 和 slice()的不同之处 , substring() 方法 无法接受负的索引
substr() 和 slice()的不同之处, substr() 第二个参数规定被提取部分的长度

9、用另一个值替换在字符串中指定的值 replace()

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

10、转换为大写和小写 转化为大写字母 toUpperCase() 转化为小写字母 toLowerCase()

11、concat() 连接两个或多个字符串

var text1 = "Hello";
var text2 = "World";
text3 = text1.concat(text2); //hello world

12、trim() 方法删除字符串两端的空白符:

13、把字符串转换为数组 split() 将字符串转换为数组

var str = 'hello world'
var res = str.split(',') //['hello', 'world']

14、match() 方法根据正则表达式在字符串中搜索匹配项,并将匹配项作为 Array 对象返回

let text = "The rain in SPAIN stays mainly in the plain";
text.match(/ain/g)    // 返回数组 [ain,ain,ain]

15、 如果字符串包含指定值,includes() 方法返回 true。

let text = "Hello world, welcome to the universe.";
text.includes("world")    // 返回 true

16、如果字符串以指定值开头,则 startsWith(searchvalue,start 可选。默认为 0。开始搜索的位置) 方法返回 true,否则返回 false

let text = "Hello world, welcome to the universe.";
text.startsWith("Hello")   // 返回 true

17、 如果字符串以指定值结尾,则 endsWith() 方法返回 true,否则返回 false

var text = "Bill Gates";
text.endsWith("Gates")    // 返回 true
posted @ 2022-09-19 12:44  boygdm  阅读(39)  评论(0编辑  收藏  举报