文章目录
- String
- 一、从字符串中获取单个字符
- 二、操作方法
- 三、检测方法
- String.prototype.startsWith(searchString,position=0)
- String.prototype.endsWith(searchString,length=str.length)
- String.prototype.includes(searchString,position=0)
- String.prototype.match()
- String.prototype.search()
- 字符串长度
- String.prototype.localeCompare()
- RegExp.prototype.exec() 与 /g
- String.prototype.padStart()
- String.prototype.substring()
- 比较
- 模板字符串
- String HTML 包装方法
String
菜鸟教程网址:https://www.runoob.com/jsref/jsref-obj-string.html
String 全局对象是一个用于字符串或一个字符序列的构造函数。
你也能使用 String 函数将其他值生成或转换成字符串:
String(thing);
new String(thing);
模板字面量
从 ECMAScript 2015 开始,字符串字面量也可以称为模板字面量:
`hello world` `hello! world!` `hello ${who}` escape `<a>${who}</a>`
字符访问
//有两种方法可以访问字符串中的单个字符。首先是 charAt()方法:
return "cat".charAt(1); // returns "a"
//复制到剪贴板
//另一种方法(在 ECMAScript 5 中引入)是将字符串视为类似数组的对象,其中单个字符对应于数字索引:
return "cat"[1]; // returns "a"
字符串.raw()
静态 String.raw()方法是模板文字的标记函数。这类似于 rPython 中的前缀,或@ C# 中字符串文字的前缀。它用于获取模板文字的原始字符串形式,即处理替换(例如 ${foo}),但不处理转义(例如\n)。
// Create a variable that uses a Windows
// path without escaping the backslashes:
const filePath = String.raw`C:\Development\profile\aboutme.html`;
console.log(`The file was uploaded from: ${filePath}`);
// expected output: "The file was uploaded from: C:\Development\profile\aboutme.html"
一、从字符串中获取单个字符
String.prototype.at()
该 at()方法接受一个整数值并返回一个 String 由位于指定偏移量处的单个 UTF-16 代码单元组成的新值。此方法允许正整数和负整数。负整数从最后一个字符串字符开始倒数。
const sentence = "The quick brown fox jumps over the lazy dog.";
let index = 5;
console.log(
`Using an index of ${index} the character returned is ${sentence.at(index)}`
);
// expected output: "Using an index of 5 the character returned is u"
index = -4;
console.log(
`Using an index of ${index} the character returned is ${sentence.at(index)}`
);
// expected output: "Using an index of -4 the character returned is d"
String.prototype.charAt()
String.prototype.charAt(index=0) —— 返回指定索引的字符串。参数的默认值为0,也就是说,没有传参就返回字符串的第一个字符。
let str = "jonas"
console.log(str.charAt())//j
const sentence = "The quick brown fox jumps over the lazy dog.";
const index = 4;
console.log(`The character at index ${index} is ${sentence.charAt(index)}`);
// expected output: "The character at index 4 is q"
String.prototype.charCodeAt(index): index(0~length-1),
返回值 :指定 index 处字符的 UTF-16 代码单元值的一个数字(0~65535);如果 index 超出范围,charCodeAt() 返回 NaN.
var a = "?"
a.charCodeAt(0);//返回前两个字节的值 55362
a.charCodeAt(1);//返回后两个字节的值 57271
var a="?c"
a.charCodeAt(0);//返回了该字的十进制码点
a.charCodeAt(1);//返回后两个字节的值
a.charCodeAt(2);//返回c的由此可见
// 上面代码中,字符c在字符串a的正确位置序号应该是 1,但是必须向codePointAt方法传入 2.
// 解决办法: 使用for...of循环, 因为它会正确识别32位的UTF-16字符.
let a = '?c';
for (let ch of a) {
console.log(ch.codePointAt(0));
}
// codePointAt()方法返回的是码点的十进制值,如果想要十六进制的值,可以使用toString方法转换一下。
a.codePointAt(0).toString(16)
String.prototype.indexOf()
该 indexOf()方法给定一个参数:要搜索的子字符串,搜索整个调用字符串,并返回指定子字符串第一次出现的索引。给定第二个参数:第二个参数表示从哪个位置开始查找,默认值为0,即查询整个字符串。
let str = "jonas"
console.log(str.indexOf("s"))//4
const paragraph =
"The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?";
const searchTerm = "dog";
const indexOfFirst = paragraph.indexOf(searchTerm);
console.log(
`The index of the first "${searchTerm}" from the beginning is ${indexOfFirst}`
);
// expected output: "The index of the first "dog" from the beginning is 40"
console.log(
`The index of the 2nd "${searchTerm}" is ${paragraph.indexOf(
searchTerm,
indexOfFirst + 1
)}`
);
// expected output: "The index of the 2nd "dog" is 52"
##### String.prototype.lastIndexOf()
返回 searchString 在字符串中最后一次出现的位置索引,第二个参数表示从哪个位置开始查找。
let str = "jonas"
console.log(str.lastIndexOf("s"))//4
const paragraph =
"The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?";
const searchTerm = "dog";
console.log(
`The index of the first "${searchTerm}" from the end is ${paragraph.lastIndexOf(
searchTerm
)}`
);
// expected output: "The index of the first "dog" from the end is 52"
二、操作方法
String.prototype.concat()
该 concat()方法将字符串参数连接到调用字符串并返回一个新字符串。
const str1 = "Hello";
const str2 = "World";
console.log(str1.concat(" ", str2));
// expected output: "Hello World"
console.log(str2.concat(", ", str1));
// expected output: "World, Hello"
String.prototype.repeat()
返回一个由 count 个字符串组成的新字符串。
const chorus = "Because I'm happy. ";
console.log(`Chorus lyrics for "Happy": ${chorus.repeat(2)}`);
// 'Chorus lyrics for "Happy": Because I'm happy. Because I'm happy. '
String.prototype.replace()
该 replace()方法返回一个新字符串,其中 a 的部分或全部匹配被 apattern 替换 replacement。Thepattern 可以是字符串或 a RegExp,并且 replacement 可以是每个匹配项调用的字符串或函数。如果 pattern 是一个字符串,则只会替换第一个匹配项。
原始字符串保持不变。
const p =
"The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?";
console.log(p.replace("dog", "monkey"));
// expected output: "The quick brown fox jumps over the lazy monkey. If the dog reacted, was it really lazy?"
const regex = /Dog/i;
console.log(p.replace(regex, "ferret"));
// expected output: "The quick brown fox jumps over the lazy ferret. If the dog reacted, was it really lazy?"
String.prototype.replaceAll()
该 replaceAll()方法返回一个新字符串,其中所有匹配的 a 都 pattern 替换为 a replacement。Thepattern 可以是字符串或 a RegExp,并且 replacement 可以是每个匹配项调用的字符串或函数。
原始字符串保持不变。
const p =
"The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?";
console.log(p.replaceAll("dog", "monkey"));
// expected output: "The quick brown fox jumps over the lazy monkey. If the monkey reacted, was it really lazy?"
// global flag required when calling replaceAll with regex
const regex = /Dog/gi;
console.log(p.replaceAll(regex, "ferret"));
// expected output: "The quick brown fox jumps over the lazy ferret. If the ferret reacted, was it really lazy?"
String.prototype.slice()
提取字符串从 [beginIndex,endIndex) 之间的字符串,第二个为非必须参数,如果省略,则截取到字符串的最后,结果返回新的字符串。
const str = "The quick brown fox jumps over the lazy dog.";
console.log(str.slice(31));
// expected output: "the lazy dog."
console.log(str.slice(4, 19));
// expected output: "quick brown fox"
console.log(str.slice(-4));
// expected output: "dog."
console.log(str.slice(-9, -5));
// expected output: "lazy"
String.prototype.split()
该 split()方法将 a 划分 String 为子字符串的有序列表,将这些子字符串放入一个数组中,并返回该数组。划分是通过搜索模式来完成的;其中模式作为方法调用中的第一个参数提供。
const str = "The quick brown fox jumps over the lazy dog.";
const words = str.split(" ");
console.log(words);
// ['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog.']
const chars = str.split("");
//chars ['T', 'h', 'e', ' ', 'q', 'u', 'i', 'c', 'k', ' ', 'b', 'r', 'o', 'w', 'n', ' ', 'f', 'o', 'x', ' ', 'j', 'u', 'm', 'p', 's', ' ', 'o', 'v', 'e', 'r', ' ', 't', 'h', 'e', ' ', 'l', 'a', 'z', 'y', ' ', 'd', 'o', 'g', '.']
console.log(chars[8]);
// expected output: "k"
const strCopy = str.split();
console.log(strCopy);
// expected output: Array ["The quick brown fox jumps over the lazy dog."]
String.prototype.trim()
trim() 方法用于删除字符串的头尾空白符,空白符包括:空格、制表符 tab、换行符等其他空白符等。
trim() 方法不会改变原始字符串。
trim() 方法不适用于 null, undefined, Number 类型。
要返回一个只从一端删除空白字符的新字符串,可以使用 trimStart() 或 trimEnd()。
const orig = " foo ";
console.log(orig.trim()); // 'foo'
三、检测方法
String.prototype.startsWith(searchString,position=0)
检测字符串是否以 searchString 开头,第二个参数是开始索引的位置,默认值为0,表示从字符串的首个字符开始检索,结果返回布尔值。
const str1 = "Saturday night plans";
console.log(str1.startsWith("Sat"));
// expected output: true
console.log(str1.startsWith("Sat", 3));
// expected output: false
String.prototype.endsWith(searchString,length=str.length)
检测字符串是否以 searchString 结尾,第二个参数表示索引,默认从最后开始检索,结果返回布尔值。
const str1 = "Cats are the best!";
console.log(str1.endsWith("best", 17));
// expected output: true
const str2 = "Is this a question";
console.log(str2.endsWith("?"));
// expected output: false
String.prototype.includes(searchString,position=0)
检测字符串是否包含 searchString,第二个参数表示从哪个索引开始检测,结果返回布尔值。
const sentence = "The quick brown fox jumps over the lazy dog.";
const word = "fox";
console.log(
`The word "${word}" ${
sentence.includes(word) ? "is" : "is not"
} in the sentence`
);
// expected output: "The word "fox" is in the sentence"
String.prototype.match()
检测字符串是否满足正则表达式 regexp,结果返回一个包含匹配结果的数组。
regexp: 一个正则表达式对象, 如果传入一个非正则表达式, 则会隐式地使用 new RegExp(obj) 将其转换为一个 RegExp.
返回值:
如果使用g标志, 返回与完整正则表达式匹配的所有结果,不会返回捕获组.
如果不使用g标志, 返回第一个完整匹配及其相关的捕获组.
附加属性:
groups: 一个命名捕获组对象,其键是捕获组名称,值是捕获组,如果未定义命名捕获组,则为 undefined。
index: 匹配的结果的开始位置.
input: 搜索的字符串.
const paragraph = "The quick brown fox jumps over the lazy dog. It barked.";
const regex = /[A-Z]/g;
const found = paragraph.match(regex);
console.log(found);
// expected output: Array ["T", "I"]
String.prototype.search()
返回值:
如果匹配成功,则search()返回正则表达式在字符串中首次匹配项的索引.否则,返回-1.配。
const paragraph =
"The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?";
// any character that is not a word character or whitespace
const regex = /[^\w\s]/g;
console.log(paragraph.search(regex));
// expected output: 43
console.log(paragraph[paragraph.search(regex)]);
// expected output: "."
字符串长度
对象的 length 属性 String 包含字符串的长度,以 UTF-16 代码单元表示。length 是字符串实例的只读数据属性。
const str = "Life, the universe and everything. Answer:";
console.log(`${str} ${str.length}`);
// expected output: "Life, the universe and everything. Answer: 42"
String.prototype.localeCompare()
该 localeCompare()方法返回一个数字,指示引用字符串是在排序顺序之前、之后还是与给定字符串相同。
const a = "réservé"; // with accents, lowercase
const b = "RESERVE"; // no accents, uppercase
console.log(a.localeCompare(b));
// expected output: 1
console.log(a.localeCompare(b, "en", { sensitivity: "base" }));
// expected output: 0
RegExp.prototype.exec() 与 /g
如果正则表达式有/g 标志,那么多次调用.exec()就会得到所有匹配的结果。如果没有匹配的结果,.exec()就会返回 null。在这之前会返回每个匹配的匹配对象。这个对象包含捕获的子字符串和更多信息。
举个例子:得到所有双引号之间的字符串
String.prototype.padStart()
该 padStart()方法用另一个字符串填充当前字符串(如果需要,可以多次),直到结果字符串达到给定长度。从当前字符串的开头应用填充。
const str1 = "5";
console.log(str1.padStart(2, "0"));
// expected output: "05"
const fullNumber = "2034399002125581";
const last4Digits = fullNumber.slice(-4);
const maskedNumber = last4Digits.padStart(fullNumber.length, "*");
console.log(maskedNumber);
// expected output: "************5581"
String.prototype.substring()
该 substring()方法返回 string 开始和结束索引之间的部分,或者返回到字符串的末尾。
const str = "Mozilla";
console.log(str.substring(1, 3));
// expected output: "oz"
console.log(str.substring(2));
// expected output: "zilla"
比较
charAt、 charCodeAt
输出指定位置的字符;
charAt: 根据索引获取指定位置的字符,和str[i]的作用一样
harCodeAt: 获取指定索引位置对应字符的ASCII码值
@params: n, 获取指定字符的索引
@return: 返回查找到的字符;
找不到charAt返回空字符串而非undefined,charCodeAt返回NaN。
let str = 'HappyEveryDay';
console.log(str.charAt(0)); // 'H'
console.log(str[0]); // 'H'
console.log(str.charAt(1000)); // ''
console.log(str.charCodeAt(0)); //72
console.log(str.charCodeAt(1000)); //NaN
console.log(String.fromCharCode(72)); //'H', 从ASCII码转为字符
substr、substring、slice
字符串的截取:
substr(n,m):从索引n开始,截取m个字符,m不写,截取到末尾, 不影响原来的字符串。
substring(n,m): 从索引n开始,截取到索引m,不包括m。[n,m),不影响原来的字符串
slice(n,m): 和substring一样,只不过slice 可以支持负数(可以倒数),其余两个方法不可以,不影响原来的字符串。
let str = 'HappyEveryDay';
let str1 = str.substr(5, 5);
console.log(str, str1); //HappyEveryDay Every
str1 = str.substring(5, 10);
console.log(str1); //Every
str1 = str.slice(-8, -3);
console.log(str.length); //可以用length+索引, 即 13-8=5,13-3=10, 和第二种方法一致。
console.log(str1); //从倒数第八个字符开始, 取到倒数第三个。 [-8,-3). Every。
indexOf、lastIndexOf、includes
3. 查找字符串中是否包含某个字符或某个整体字符串。
indexOf:
@params: (str,m), 从索引m开始查找,是否含有str字符或整体字符串的第一个索引位置;
@return:返回找到的第一个索引值, 找不到返回-1
lastIndexOf:
@params: (str,m), 从索引m开始查找,是否含有str字符或整体字符串的最后一个索引位置;
@return:返回找到的最后一个索引值, 找不到返回-1
includes :
@params:str, 查找当前字符串中是否含有某个str;
@return: 如果有,返回true, 否则返回false
let str = 'HappyEveryDay';
let n = str.indexOf('a');
let m = str.indexOf('Day');
let x = str.indexOf('*');
console.log(n, m, x); //1 10 -1
let n1 = str.lastIndexOf('a');
let m1 = str.lastIndexOf('Day');
let x1 = str.lastIndexOf('*');
console.log(n1, m1, x1); //11 10 -1
let con = str.includes('*');
console.log(con); //false
con = str.includes('Day');
console.log(con); //true
toUpperCase、toLowerCase
大小写转换
toUpperCase:
* @params:无;
* @return: 返回大写的字符串, 不影响原来的字符串
toLowerCase:
let str = 'HappyEveryDay';
let str1 = str.toUpperCase();
console.log(str, str1); //HappyEveryDay HAPPYEVERYDAY
let str2 = str.toLowerCase();
console.log(str, str2); //HappyEveryDay happyeveryday
// 仅字符串首字母大写
str = str.slice(0, 1).toUpperCase() + str.slice(1).toLowerCase();
console.log(str); //Happyeveryday
模板字符串
模板字符串(template string)是增强版的字符串,用反引号(`)标识。
它可以当作普通字符串使用,也可以用来定义多行字符串,
或者在字符串中嵌入变量。
// 普通字符串
`In JavaScript '\n' is a line-feed.`
// 多行字符串
`In JavaScript this is
not legal.`
console.log(`string text line 1
string text line 2`);
// 字符串中嵌入变量
let name = "Bob", time = "today";
`Hello ${name}, how are you ${time}?`
如果使用模板字符串表示多行字符串,所有的空格和缩进都会被保留在输出之中。
$('#list').html(`
<ul>
<li>first</li>
<li>second</li>
</ul>
`.trim());
模板字符串中嵌入变量,需要将变量名写在${}之中。
function authorize(user, action) {
if (!user.hasPrivilege(action)) {
throw new Error(
// 传统写法为
// 'User '
// + user.name
// + ' is not authorized to do '
// + action
// + '.'
`User ${user.name} is not authorized to do ${action}.`);
}
}
大括号内部可以放入任意的 JavaScript 表达式,可以进行运算,以及引用对象属性。
let x = 1;
let y = 2;
`${x} + ${y} = ${x + y}`
// "1 + 2 = 3"
`${x} + ${y * 2} = ${x + y * 2}`
// "1 + 4 = 5"
let obj = {x: 1, y: 2};
`${obj.x + obj.y}`
// "3"
模板字符串之中还能调用函数。
function fn() {
return "Hello World";
}
`foo ${fn()} bar`
// foo Hello World bar
String HTML 包装方法
sub() 方法用于把字符串显示为下标。
该方法返回加入 标签的字符串,如下所示:
string
document.write("<p>下标: " + txt.sub() + "</p>");
document.write("<p>上标: " + txt.sup() + "</p>");
```