# 字符串string

anchor()	创建 HTML 锚。
concat()	连接字符串。
fixed()	以打字机文本显示字符串。
link()	将字符串显示为链接。
localeCompare()	用本地特定的顺序来比较两个字符串。
match()	找到一个或多个正则表达式的匹配。
replace()	替换与正则表达式匹配的子串。
search()	检索与正则表达式相匹配的值。
slice()	提取字符串的片断,并在新的字符串中返回被提取的部分。
split()	把字符串分割为字符串数组。
strike()	使用删除线来显示字符串。
sub()	把字符串显示为下标。
sup()	把字符串显示为上标。
toSource()	代表对象的源代码。
toString()	返回字符串。
valueOf()	返回某个字符串对象的原始值。
trimLeft() 清除左侧空格=>【trimStart() MDN支持这种写法】
trimRight() 清除右侧空格=>【trimEnd() 方法从一个字符串的末端移除空白字符。trimRight() 是这个方法的别名。】
trim() 清除两边空格
localeCompare()单词排序可以使用

# includes()

返回布尔值,判断是否找到参数字符串

# startsWith()

返回布尔值,判断参数字符串是否在原字符串的头部

# endsWith()

返回布尔值,判断参数字符串是否在原字符串的尾部。

以上三个方法都可以接受两个参数,需要搜索的字符串,和可选的搜索起始位置索引。

let string = "apple,banana,orange";
string.includes("banana");     // true
string.startsWith("apple");    // true
string.endsWith("apple");      // false
string.startsWith("banana",6)  // true
string.includes("apple",10) //false
string.includes("apple",0)//true
# repeat()

repeat():返回新的字符串,表示将字符串重复指定次数返回。如果参数是小数,向下取整

console.log("Hello,".repeat(3.2));  // "Hello,Hello,Hello,"

# padStart() padEnd()

返回新的字符串,表示用参数字符串从(padStart左侧/(padEnd()右侧)补全原字符串。第一个参数是指定生成的字符串的最小长度,第二个参数是用来补全的字符串。如果没有指定第二个参数,默认用空格填充。如果指定的长度小于或者等于原字符串的长度,则返回原字符串.如果原字符串加上补全字符串长度大于指定长度,则截去超出位数的补全字符串.

console.log("h".padStart(5,"o"));  // "ooooh"
console.log("h".padEnd(5,"o"));    // "hoooo"
console.log("h".padStart(5));      // "    h"
console.log("hello".padStart(5,"A"));  // "hello"
console.log("hello".padEnd(10,",world!"));  // "hello,worl"
console.log("123".padStart(10,"0"));  // "0000000123"

# slice切割字符串

var str ="djqfwq";
str.slice(1,4)//jqf
//原字符串不变
<html>
<body class="m-2">
	<div id="k">JHLP</div>

</body>

</html>
<script>
	let k = document.getElementById("k")
	k.onclick=function(){
		k.innerHTML= k.innerHTML.link('https://www.baidu.com')
	}
</script>

# 字符串其他方法

  • charAt() 返回在指定位置的字符,可找到某个或者某些字符,比如大小写切换
  • concat() 连接两个或更多字符串,并返回新的字符串
"3".concat("4",5)
//345
  • indexOf() 返回某个指定的字符串值在字符串中首次出现的位置。
  • toLocaleLowerCase() 切换小写
  • valueOf() 返回某个字符串对象的原始值。
  • toString() 返回一个字符串。
  • trim() 去除字符串两边的空白

# 对比slice substring substr

首先,他们都接收两个参数,slice和substring接收的是起始位置和结束位置(不包括结束位置),而substr接收的则是起始位置和所要返回的字符串长度。直接看下面例子:

    var test = 'hello world';
 
    alert(test.slice(4,7));             //o w
    alert(test.substring(4,7));         //o w
    alert(test.substr(4,7));            //o world

这里有个需要注意的地方就是:substring是以两个参数中较小一个作为起始位置,较大的参数作为结束位置。

如:

alert(test.substring(7,4));          //o w

接着,当接收的参数是负数时,slice会将它字符串的长度与对应的负数相加,结果作为参数substr如果第一个参数 < 0,则索引从字符串末尾开始计数,如果第二个参数小于0,直接返回空字符串;substring则干脆将负参数都直接转换为0。测试代码如下:

var test = 'hello world';
 
 console.log(test.slice(-3));         //rld
 console.log(test.substring(-3));     //hello world
 console.log(test.substr(-3));        //rld

 console.log(test.slice(3,-4));       //lo w
 console.log(test.substring(3,-4));   //hel
 console.log(test.substr(3,-4));      //空字符串

注意:IE对substr接收负值的处理有错,它会返回原始字符串。

  • split() 把字符串分割为字符串数组。
var str = "姓名+研究编号+年龄"
var  res = str.split(/[+]/);
console.log(res)
//["姓名", "研究编号", "年龄"]
  • split还可以限制生成的数组位数
let colorText = "red,blue,green,yellow";
let colors1 = colorText.split(",");       // ["red", "blue", "green", "yellow"]
let colors2 = colorText.split(",", 2);    // ["red", "blue"]
let colors3 = colorText.split(/[e]+/);  // ['r', 'd,blu', ',gr', 'n,y', 'llow']
console.log(colors1)
console.log(colors2)
console.log(colors3)
  • search() 查找与正则表达式相匹配的值。没有返回-1
var str="Visit Runoob!"; 
var n=str.search("Runoob");
//6
let text = "cat,bat,sat,fat";
let pos = text.search(/at,f/);
console.log(pos); // 9
  • replace() 在字符串中查找匹配的子串, 并替换与正则表达式匹配的子串。
var str="Visit Microsoft! Visit Microsoft!";
var n=str.replace("Microsoft","Runoob");
//"Visit Runoob! Visit Microsoft!"
var str="Mr Blue has a blue house and a blue car";
var n=str.replace(/blue/g,"red");
//"Mr Blue has a red house and a red car"
  • replace 第二个参数可以是个函数
function htmlEscape(text) {
  return text.replace(/[<>"&]/g, function(match, pos, originalText) {
    switch(match) {
      case "<":
        return "&lt;";
      case ">":
        return "&gt;";
      case "&":
        return "&amp;";
      case "\"":
        return "&quot;";
    }       
  });
}
         
console.log(htmlEscape("<p class=\"greeting\">Hello world!</p>")); 
// "&lt;p class=&quot;greeting&quot;&gt;Hello world!&lt;/p&gt;"

# replace replaceAll

使用 replaceAll

'aabbcc'.replaceAll('b', '.');
// 'aa..cc'
  • 非全局 regex 抛出:使用正则表达式搜索值时,它必须是全局的。这将行不通:
'aabbcc'.replaceAll(/b/, '.');
//TypeError: replaceAll must be called with a global RegExp

这将可以正常运行:

'aabbcc'.replaceAll(/b/g, '.');
//"aa..cc"

# replace 和 replaceAll

方法解释:两种方法都返回一个新字符串,原始字符串保持不变。并且改方法可以传两个参数。

  • 参数一:pattern。 pattern 可以是一个 字符串 或一个 正则表达式,
  • 参数二:replacement。 replacement 可以是一个字符串或一个在每次匹配被调用的函数。
  1. 当 pattern 是字符串时,replace 只替换匹配到的第一个位置,replaceAll 会替换每一个匹配到的地方。
var value = '123-234-234-234'
var pattern = '-'
console.log('replace: ' + value.replace(pattern, '/'))   
console.log('replaceAll: ' + value.replaceAll(pattern, '/'))

// 输出:
// replace: 123/234-234-234
// replaceAll: 123/234/234/234
  1. 当 pattern 都是正则表达式时,没有区别。
var value = '123-234-234-234'
var pattern = /-/g
console.log('replace: ' + value.replace(pattern, '/'))   
console.log('replaceAll: ' + value.replaceAll(pattern, '/'))

// 输出:
// replace: 123/234/234/234
// replaceAll: 123/234/234/234

除此之外,两个函数的第二个参数都可以传入一个函数,用来自定义替换规则。

var value = '123-234-234-234'
var pattern = '-'
let value1=value.replace(pattern, (item, index) => {
	// item 替换元素,index 替换元素的下标
	console.log(item, index)
	return '/'
})

let value2=value.replaceAll(pattern, (item, index) => {
	// item 替换元素,index 替换元素的下标
	console.log(item, index)
	return '/'
})

// 输出:
// - 3

//- 3
//- 7
//- 11

console.log(value1,value2)
// 123/234-234-234 123/234/234/234

# match

  • match() 查找找到一个或多个正则表达式的匹配。
var str="The rain in SPAIN stays mainly in the plain"; 
var n=str.match(/ain/g);
//ain,ain,ain

如果不加g 结果呈现的结果是["ain", index: 5, input: "The rain in SPAIN stays mainly in the plain", groups: undefined],可以n.index,n.input拿到这些数据。只是浏览器的展示问题,实际只是找到第一个["ain"],但是没太大意义。

如果存在小括号的情况处理

// // 传统方式
function query(name) {
    const search = location.search.substr(1) // 类似 array.slice(1)
    // http://127.0.0.1:8848/template/1.html?a=30&b=40&c=50&d=60
    const reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`, 'i')
    const res = search.match(reg)
    console.warn(res)
    if (res === null) {
        return null
    }
    return res[2]
}
// 第一位匹配到的全局,后面依次是每个小括号对应的
// ([^&]*):非&符号的内容
console.warn(query('a'))
//  ['&c=50&', '&', '50', '&', index: 9, input: 'a=30&b=40&c=50&d=60', groups: undefined]
console.warn(query('c'))
// ['a=30&', '', '30', '&', index: 0, input: 'a=30&b=40&c=50&d=60', groups: undefined]

# matchAll

matchAll() 方法返回一个包含所有匹配正则表达式的结果及其分组捕获组的 迭代器,返回值:可以使用for…of…,数组新增的扩展符(…)或Array.from()实现功能

const str = 'hello javascript hello css'
console.log(...str.matchAll(/hello/g))
// [0: "hello", groups: undefined, index: 0, input: "hello javascript hello css"]
// [0: "hello", groups: undefined, index: 17, input: "hello javascript hello css"]

// 0: "hello"  匹配的字符串,如果有使用分组会在后面依次列出来
// groups: undefined  没有使用命名捕获组会返回undefined,否则会返回包含命名捕获组的对象
// index: 0  匹配的结果在当前字符串位置开始的索引
// input: "hello javascript hello css" 当前字符串
const str = 'hello javascript hello css'
console.log(...str.match(/hello/g))//hello hello

# 对比

var s ="t1 t2 t3"
console.log(s.search(/t2/))	
console.log(s.search("t2"))	
console.log(s.indexOf("t2",4))
console.log(s.includes("t2",3))
//3 3 -1 true

# 模板字符串``

模板字符串支持标签函数,标签函数:这里的形参其实接收的是字符串模板中除去${}之外的字符串所组成的数组,每一个${}都相当于一个分隔符,而想要接收${}所表示的字符串,需要额外的形参,有几个${}就需要多几个形参,

function foo(a,b,c){
	console.log(a)
	console.log(b)
	console.log(c)
}
let par1 = "第一个参数"
let par2 = "第二个参数"
foo`abc${par1}def${par2}gh`
// (3) ['abc', 'def', 'gh', raw: Array(3)]0: "abc"1: "def"2: "gh"length: 3raw: (3) ['abc', 'def', 'gh'][[Prototype]]: Array(0)
// 第一个参数
//  第二个参数

# String.raw

不转义原字符串的函数

let a=`\u00A9`
console.log(a)//©
let b="\u00A9"
console.log(b)//©
console.log(String.raw`\u00A9`)//\u00A9
console.log(String.raw`${a}`)//©

# 字符串@@iterator 迭代与解构赋值

字符串原型上暴露了@@iterator,可以迭代与解构赋值

let message = "abc";
let stringIterator = message[Symbol.iterator]();

console.log(stringIterator.next());  // {value: "a", done: false}
console.log(stringIterator.next());  // {value: "b", done: false}
console.log(stringIterator.next());  // {value: "c", done: false}
console.log(stringIterator.next());  // {value: undefined, done: true}

for (const c of "abcde") {
  console.log(c);
  //a 
  //b 
  //c 
  //d 
  //e
}
let f='abcde'
console.log([...f])//['a', 'b', 'c', 'd', 'e']

# string 大小写 toUpperCase toLowerCase

  • 优先使用 toLocaleUpperCase/toLocaleLowerCase
let stringValue = "hello world";
console.log(stringValue.toLocaleUpperCase());  // "HELLO WORLD"
console.log(stringValue.toUpperCase());        // "HELLO WORLD"
console.log(stringValue.toLocaleLowerCase());  // "hello world"
console.log(stringValue.toLowerCase());        // "hello world"

# 字符串使用$匹配捕获组

let text = "cat, bat, sat, fat";    
result = text.replace(/(.at)/g, "word ($1)");
console.log(result);  // word (cat), word (bat), word (sat), word (fat)

# localCompare

用于排序单词顺序

let stringValue = "yellow";   
console.log(stringValue.localeCompare("brick"));  // 1
console.log(stringValue.localeCompare("yellow")); // 0
console.log(stringValue.localeCompare("zoo"));  // -1

# string normalize

Unicode 标准化:Unicode 标准化(Unicode Normalization),也叫 Unicode 正规化或Unicode 规范化,可将字符转换成指定的字节序列,统一表现形式,以及确定字符之间的等价性。如字符“ü”,既可以只用 U+00FC 表示,也可以用 U+0075(u)和 U+0308(¨)组合表示,虽然对于人类来说,两种表示法得到的结果在视觉上是完全相同的,但对于计算机来说却是不同的,如下所示。

var mark1 = "\u00FC",
 mark2 = "\u0075\u0308";
mark1 === mark2; //false

ES6 新增了一个原型方法 normalize(),可以将字符串标准化,修改上面的例子,就能得到相等的结果,如下所示。

mark1.normalize() === mark2.normalize(); //true

normalize()方法可以接收一个字符串参数,但只有 4 个可选值,如表 1-4 所示,其中“NFC”是方法的默认值。

可选值 作用描述
NFD 标准等价分解
NFC 先以标准等价分解,再以标准等价合成
NFKD 兼容等价分解
NFKC 先以兼容等价分解,再以标准等价合成

表中的标准等价(Canonical Equivalence)和兼容等价(Compatibility Equivalence)都表示相同的字符或字符序列,并且前者是后者的一个子集。标准等价会保持视觉外观和文本含义,前面字符“ü”的示例就用到了标准等价;而兼容等价会改变视觉外观和文本含义,例如,罗马数字十二(Ⅻ)可由一个罗马数字十(Ⅹ)和两个罗马数字一(Ⅰ)组成,两者只有通过兼容等价的标准化处理后才能匹配成功,如下所示。

var digit1 = "\u216B", //"Ⅻ"
 digit2 = "\u2169\u2160\u2160"; //"ⅩⅠⅠ"
digit1 = digit1.normalize("NFKC"); //"XII"
digit2 = digit2.normalize("NFKC"); //"XII"
digit1 === digit2; //true 
最后更新: 11/21/2024, 2:37:03 PM