Home > Web Front-end > JS Tutorial > body text

A detailed introduction to common basic methods of JavaScript strings

WBOY
Release: 2022-05-25 11:59:05
forward
2681 people have browsed it

This article brings you relevant knowledge about javascript, which mainly introduces the relevant knowledge about strings, which mainly introduces the commonly used basic methods as well as special characters and A detailed introduction to common basic methods of JavaScript strings internal representation methods. Let’s take a look at the content below, I hope it will be helpful to everyone.

A detailed introduction to common basic methods of JavaScript strings

[Related recommendations: javascript video tutorial, web front-end]

No matter what programming language In , strings are important data types. Follow me to learn moreJavaScript string knowledge!

Preface

A string is a string composed of characters. If you have studied C, Java, you should know that the characters themselves can also independently become a type. However, JavaScript does not have a single character type, only a string of length 1. The string of

JavaScript uses a fixed UTF-16 encoding. No matter what encoding we use when writing the program, it will not be affected.

Writing

There are three ways to write strings: single quotes, double quotes, and backticks.

let single = 'abcdefg';//单引号let double = "asdfghj";//双引号let backti = `zxcvbnm`;//反引号
Copy after login

Single and double quotation marks have the same status, we do not make a distinction.

String formatting

Backticks allow us to use ${...}elegantly format strings instead of using strings Addition operation.

let str = `I'm ${Math.round(18.5)} years old.`;console.log(str);
Copy after login

Code execution result:

A detailed introduction to common basic methods of JavaScript strings

Multi-line string

Backticks can also allow strings to span lines , very useful when we write multi-line strings.

let ques = `Is the author handsome?
A. Very handsome;
B. So handsome;
C. Super handsome;`;console.log(ques);
Copy after login

Code execution result:

A detailed introduction to common basic methods of JavaScript strings

Doesn’t it seem like there is nothing? However, this cannot be achieved using single and double quotes. If you want to get the same result, you can write:

let ques = 'Is the author handsome?\nA. Very handsome;\nB. So handsome;\nC. Super handsome;';console.log(ques);
Copy after login

The above code contains a special character \n, which is used in our programming process The most common special characters.

Special characters

Characters\n, also known as "newline character", supports single and double quotes to output multi-line strings. When the engine outputs a string, if it encounters \n, it will continue to output on another line, thereby realizing a multi-line string.

Although \n looks like two characters, it only occupies one character position. This is because \ is the escape character in the string. , characters modified by escape characters become special characters.

Special character list

Single and double quotation marks, mainly because single and double quotation marks are special characters, we want When using single and double characters in a string, escape them. Backslash, also because Backspace, page feed, vertical tabs - are no longer used. is a hexadecimal is a hexadecimal

举个例子:

console.log('I\'m a student.');// \'console.log("\"I love U\"");// \"console.log("\\n is new line character.");// \nconsole.log('\u00A9')// ©console.log('\u{1F60D}');//
Copy after login

代码执行结果:

A detailed introduction to common basic methods of JavaScript strings

有了转义符\的存在,理论上我们可以输出任何字符,只要找到它对应的编码就可以了。

避免使用\'\"

对于字符串中的单双引号,我们可以通过在单引号中使用双引号、在双引号中使用单引号,或者直接在反引号中使用单双引号,就可以巧妙的避免使用转义符,例如:

console.log("I'm a student.");
//双引号中使用单引号console.log('"" is used.');
//单引号中使用双引号console.log(`' " is used.`);
//反引号中使用单双引号
Copy after login

代码执行结果如下:

A detailed introduction to common basic methods of JavaScript strings

.length

通过字符串的.length属性,我们可以获得字符串的长度:

console.log("HelloWorld\n".length);//11
Copy after login

这里\n只占用了一个字符。

《基础类型的方法》章节我们探究了JavaScript中的基础类型为什么会有属性和方法,你还记得吗?

访问字符、charAt()、for…of

字符串是字符组成的串,我们可以通过[字符下标]访问单个的字符,字符下标从0开始:

let str = "The author is handsome.";
console.log(str[0]);//Tconsole.log(str[4]);//aconsole.log(str[str.length-1]);//.
Copy after login

代码执行结果:

A detailed introduction to common basic methods of JavaScript strings

我们还可以使用charAt(post)函数获得字符:

let str = "The author is handsome.";console.log(str.charAt(0));
//Tconsole.log(str.charAt(4));
//aconsole.log(str.charAt(str.length-1));//.
Copy after login

二者执行效果完全相同,唯一的区别在于越界访问字符时:

let str = "01234";console.log(str[9]);//undefinedconsole.log(str.charAt(9));//""(空串)
Copy after login

我们还可以使用for ..of遍历字符串:

for(let c of '01234'){
    console.log(c);}
Copy after login

字符串不可变

JavaScript中的字符串一经定义就不可更改,举个例子:

let str = "Const";str[0] = 'c' ;console.log(str);
Copy after login

代码执行结果:

A detailed introduction to common basic methods of JavaScript strings

如果想获得一个不一样的字符串,只能新建:

let str = "Const";str = str.replace('C','c');console.log(str);
Copy after login

看起来我们似乎改变了字符串,实际上原来的字符串并没有被改变,我们得到的是replace方法返回的新字符串。

.toLowerCase()、.toUpperCase()

转换字符串大小写,或者转换字符串中单个字符的大小写。

这两个字符串的方法比较简单,举例带过:

console.log('Good Boy'.toLowerCase());//good 
boyconsole.log('Good Boy'.toUpperCase());//GOOD 
BOYconsole.log('Good Boy'[5].toLowerCase());//b
Copy after login

代码执行结果:

A detailed introduction to common basic methods of JavaScript strings

.indexOf()、.lastIndexOf() 查找子串

.indexOf(substr,idx)函数从字符串的idx位置开始,查找子串substr的位置,成功返回子串首字符下标,失败返回-1

let str = "google google";console.log(str.indexOf('google'));
//0 idx默认为0console.log(str.indexOf('google',1));
//7 从第二个字符开始查找console.log(str.indexOf('xxx'));
//-1 没找到返回-1
Copy after login

代码执行结果:

A detailed introduction to common basic methods of JavaScript strings

如果我们想查询字符串中所有子串位置,可以使用循环:

let str = "I love love love love u.";let sub = "love";let pos = -1;while((pos = str.indexOf(sub,pos+1)) != -1)
    console.log(pos);
Copy after login

代码执行结果如下:

A detailed introduction to common basic methods of JavaScript strings

.lastIndexOf(substr,idx)倒着查询子串,首先查找最后一个符合的串:

let str = "google google";console.log(str.lastIndexOf('google'));//7 idx默认为0
Copy after login

按位取反技巧(不推荐,但要会)

由于indexOf()lastIndexOf()方法在查询不成功的时候会返回-1,而~-1 === 0。也就是说只有在查询结果不为-1的情况下使用~才为真,所以我们可以:

let str = "google google";if(~indexOf('google',str)){
    ...}
Copy after login

通常情况下,我们不推荐在不能明显体现语法特性的地方使用一个语法,这会在可读性上产生影响。好在以上代码只出现在旧版本的代码中,这里提到就是为了大家在阅读旧代码的时候不会产生困惑。

补充:

~是按位取反运算符,例如:十进制的数字2的二进制形式为0010~2的二进制形式就是1101(补码),也就是-3

简单的理解方式,~n等价于-(n+1),例如:~2 === -(2+1) === -3

.includes()、.startsWith()、.endsWith()

  1. .includes(substr,idx)用于判断substr是否在字符串中,idx是查询开始的位置

    console.log('Google Google'.includes('Google'));//trueconsole.log('Google Google'.includes('xxxxxx'));//falseconsole.log('9966'.includes('99',1));//false
    Copy after login

    代码执行结果:

    A detailed introduction to common basic methods of JavaScript strings

  2. .startsWith('substr').endsWith('substr')分别判断字符串是否以substr开始或结束

    console.log("google".startsWith('go'));//trueconsole.log('google'.endsWith('le'));//trueconsole.log('google'.endsWith('ie'));//false
    Copy after login

    代码执行结果:

    A detailed introduction to common basic methods of JavaScript strings

.A detailed introduction to common basic methods of JavaScript strings、.A detailed introduction to common basic methods of JavaScript strings、.A detailed introduction to common basic methods of JavaScript strings

.A detailed introduction to common basic methods of JavaScript strings.A detailed introduction to common basic methods of JavaScript strings.A detailed introduction to common basic methods of JavaScript strings均用于取字符串的子串,不过用法各有不同。

  1. .substr(start,len)

    返回字符串从start开始len个字符组成的字符串,如果省略len,就截取到原字符串的末尾。start可以为负数,表示从后往前第start个字符。

    let str = "0123456789";console.log(str.substr(1))//123456789,从1开始到最后console.log(str.substr(3,2))//34,从3开始的2个字符console.log(str.substr(-3,2))//78,倒数第二个开始
    Copy after login

    代码执行结果:

    A detailed introduction to common basic methods of JavaScript strings

  2. .slice(start,end)

    返回字符串从start开始到end结束(不包括)的字符串。startend可以为负数,表示倒数第start/end个字符。

    let str = '0123456789';console.log(str.slice(1,5));//1234,区间[1,5)之间的字符console.log(str.slice(1));//123456789,从1到结尾console.log(str.slice(-4,-1));//678,倒数第四个到倒数第1个
    Copy after login

    代码执行结果:

    A detailed introduction to common basic methods of JavaScript strings

  3. .substring(start,end)

    作用几乎和.A detailed introduction to common basic methods of JavaScript strings相同,差别在两个地方:

    • 允许end > start;
    • 不允许负数,负数视为0;

    举例:

    let str = '0123456789';console.log(str.substring(1,3));//12console.log(str.substring(3,1));//12console.log(str.substring(-1,3));//012,-1被当作0
    Copy after login

    代码执行结果:

    A detailed introduction to common basic methods of JavaScript strings

对比三者的区别:

Special character Description
\n Newline character, used to start a new line of output text.
\r Carriage return character, move the cursor to the beginning of the line, use ## in Windows system #\r\n represents a line break, which means that the cursor needs to go to the beginning of the line first, and then to the next line before it can change to a new line. For other systems, just use \n.
\' \"
\\ \ is a special character. If we just want to output \ itself, we must escape it.
\b \ f \v
\xXX Unicode character encoded as XX, for example: \x7A means z ( The hexadecimal Unicode encoding of z is 7A).
\uXXXX Unicode character encoded as XXXX, for example: \u00A9 means ©.
\u{X...X} (1-6 hexadecimal characters) UTF-32The Unicode symbol encoded as X...X.
方法 描述 参数
.slice(start,end) [start,end) 可负
.substring(start,end) [start,end) 负值为0
.substr(start,len) start开始长为len的子串 可负

方法多了自然就选择困难了,这里建议记住.A detailed introduction to common basic methods of JavaScript strings就可以了,相比于其他两种更灵活。

.A detailed introduction to common basic methods of JavaScript strings、A detailed introduction to common basic methods of JavaScript strings

我们在前文中已经提及过字符串的比较,字符串按照字典序进行排序,每个字符背后都是一个编码,ASCII编码就是一个重要的参考。

例如:

console.log('a'>'Z');//true
Copy after login

字符之间的比较,本质上是代表字符的编码之间的比较。JavaScript使用UTF-16编码字符串,每个字符都是一个16为的代码,想要知道比较的本质,就需要使用.codePointAt(idx)获得字符的编码:

console.log('a'.codePointAt(0));//97console.log('Z'.codePointAt(0));//90
Copy after login

代码执行结果:

A detailed introduction to common basic methods of JavaScript strings

使用String.fromCodePoint(code)可以把编码转为字符:

console.log(String.fromCodePoint(97));console.log(String.fromCodePoint(90));
Copy after login

代码执行结果如下:

A detailed introduction to common basic methods of JavaScript strings

这个过程可以用转义符\u实现,如下:

console.log('\u005a');//Z,005a是90的16进制写法console.log('\u0061');//a,0061是97的16进制写法
Copy after login

下面我们探索一下编码为[65,220]区间的字符:

let str = '';for(let i = 65; i<p>代码执行部分结果如下:</p><p><img src="https://img.php.cn/upload/article/000/000/067/0f4e2a78ef52090d845bd32f6b72d01c-17.png" alt="A detailed introduction to common basic methods of JavaScript strings"></p><p>上图并没有展示所有的结果,快去试试吧。</p><h2>.localeCompare()</h2><p>基于国际化标准<code>ECMA-402</code>,<code>JavaScript</code>已经实现了一个特殊的方法(<code>.localeCompare()</code>)比较各种字符串,采用<code>str1.localeCompare(str2)</code>的方式:</p><ol>
<li>如果<code>str1 ,返回负数;</code>
</li>
<li>如果<code>str1 > str2</code>,返回正数;</li>
<li>如果<code>str1 == str2</code>,返回0;</li>
</ol><p>举个例子:</p><pre class="brush:php;toolbar:false">console.log("abc".localeCompare('def'));//-1
Copy after login

为什么不直接使用比较运算符呢?

这是因为英文字符有一些特殊的写法,例如,áa的变体:

console.log('á' <p>虽然也是<code>a</code>,但是比<code>z</code>还要大!!</p><p>此时就需要使用<code>.localeCompare()</code>方法:</p><pre class="brush:php;toolbar:false">console.log('á'.localeCompare('z'));//-1
Copy after login

常用方法

  1. str.trim()去除字符串前后空白字符,str.trimStart()str.trimEnd()删除开头、结尾的空格;

    let str = "  999   ";console.log(str.trim());//999
    Copy after login
  2. str.repeat(n)重复n次字符串;

    let str = '6';console.log(str.repeat(3));//666
    Copy after login
  3. str.replace(substr,newstr)替换第一个子串,str.replaceAll()用于替换所有子串;

    let str = '9+9';console.log(str.replace('9','6'));//6+9console.log(str.replaceAll('9','6'));//6+6
    Copy after login

还有很多其他方法,我们可以访问手册获取更多知识。

进阶内容

生僻字、A detailed introduction to common basic methods of JavaScript strings、特殊符号

JavaScript使用UTF-16编码字符串,也就是使用两个字节(16位)表示一个字符,但是16位数据只能表示65536个字符,对于常见字符自然不在话下,但是对于生僻字(中文的)、A detailed introduction to common basic methods of JavaScript strings、罕见数学符号等就力不从心了。

这种时候就需要扩展,使用更长的位数(32位)表示特殊字符,例如:

console.log(''.length);//2console.log('?'.length);//2
Copy after login

代码执行结果:

A detailed introduction to common basic methods of JavaScript strings

这么做的结果是,我们无法使用常规的方法处理它们,如果我们单个输出其中的每个字节,会发生什么呢?

console.log(''[0]);console.log(''[1]);
Copy after login

代码执行结果:

A detailed introduction to common basic methods of JavaScript strings

可以看到,单个输出字节是不能识别的。

好在A detailed introduction to common basic methods of JavaScript strings.A detailed introduction to common basic methods of JavaScript strings两个方法是可以处理这种情况的,这是因为二者是最近才加入的。在旧版本的JavaScript中,只能使用String.fromCharCode().charCodeAt()两个方法转换编码和字符,但是他们不适用于特殊字符的情况。

我们可以通过判断一个字符的编码范围,判断它是否是一个特殊字符,从而处理特殊字符。如果一个字符的代码在0xd800~0xdbff之间,那么他是32位字符的第一部分,它的第二部分应该在0xdc00~0xdfff

举个例子:

console.log(''.charCodeAt(0).toString(16));//d83
dconsole.log('?'.charCodeAt(1).toString(16));//de02
Copy after login

代码执行结果:

A detailed introduction to common basic methods of JavaScript strings

规范化

在英文中,存在很多基于字母的变体,例如:字母 a 可以是 àáâäãåā 的基本字符。这些变体符号并没有全部存储在UTF-16编码中,因为变化组合太多了。

为了支持所有的变体组合,同样使用多个Unicode字符表示单个变体字符,在编程过程中,我们可以使用基本字符加上“装饰符号”的方式表达特殊字符:

console.log('a\u0307');//ȧ
console.log('a\u0308');//ȧ
console.log('a\u0309');//ȧ
console.log('E\u0307');//Ė
console.log('E\u0308');//Ë
console.log('E\u0309');//Ẻ
Copy after login

代码执行结果:

A detailed introduction to common basic methods of JavaScript strings

一个基础字母还可以有多个装饰,例如:

console.log('E\u0307\u0323');//Ẹ̇
console.log('E\u0323\u0307');//Ẹ̇
Copy after login

代码执行结果:

A detailed introduction to common basic methods of JavaScript strings

这里存在一个问题,在多个装饰的情况下,装饰的排序不同,实际上展示的字符是一样的。

如果我们直接比较这两种表示形式,却会得到错误的结果:

let e1 = 'E\u0307\u0323';
let e2 = 'E\u0323\u0307';
console.log(`${e1}==${e2} is ${e1 == e2}`)
Copy after login

代码执行结果:

A detailed introduction to common basic methods of JavaScript strings

为了解决这种情况,有一个**Unicode规范化算法,可以将字符串转为通用**格式,由str.normalize()实现:

<span   style="max-width:90%" microsoft yahei sans gb helvetica neue tahoma arial sans-serif>let e1 = 'E\u0307\u0323';<br>let e2 = 'E\u0323\u0307';<br>console.log(`${e1}==${e2} is ${e1.normalize() == e2.normalize()}`)</span><br>
Copy after login

代码执行结果:

A detailed introduction to common basic methods of JavaScript strings

【相关推荐:javascript视频教程web前端

The above is the detailed content of A detailed introduction to common basic methods of JavaScript strings. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!