iis服务器助手广告广告
返回顶部
首页 > 资讯 > 前端开发 > JavaScript >梳理总结JavaScript的23个String方法
  • 817
分享到

梳理总结JavaScript的23个String方法

2024-04-02 19:04:59 817人浏览 八月长安
摘要

目录简单介绍1、charAt()2、charCodeAt()3、codePointAt()4、indexOf()5、lastIndexOf()6、startsWith()7、ends

简单介绍

javascript 中的String类型用于表示文本型的数据。它是由无符号整数值(16bit)作为元素而组成的集合字符串中的每个元素在字符串中占据一个位置. 第一个元素的 index 值是 0,下一个元素的 index 值是 1,以此类推。字符串的长度就是字符串中所含的元素个数.你可以通过 String 字面值或者 String 对象两种方式创建一个字符串。

1、charAt()

字符串中的字符从左向右索引,第一个字符的索引值为 0,最后一个字符(假设该字符位于字符串 stringName 中)的索引值为 stringName.length - 1。 如果指定的 index 值超出了该范围,则返回一个空字符串

var anyString = "Brave new world";

console.log("The character at index 0   is '" + anyString.charAt(0)   + "'");
console.log("The character at index 1   is '" + anyString.charAt(1)   + "'");
console.log("The character at index 2   is '" + anyString.charAt(2)   + "'");
console.log("The character at index 3   is '" + anyString.charAt(3)   + "'");
console.log("The character at index 4   is '" + anyString.charAt(4)   + "'");
console.log("The character at index 999 is '" + anyString.charAt(999) + "'");

输出:

The character at index 0 is 'B'
The character at index 1 is 'r'
The character at index 2 is 'a'
The character at index 3 is 'v'
The character at index 4 is 'e'
The character at index 999 is ''

2、charCodeAt()

返回 0 到 65535 之间的整数,表示给定索引处的 UTF-16 代码单元

"ABC".charCodeAt(0) // returns 65:"A"

"ABC".charCodeAt(1) // returns 66:"B"

"ABC".charCodeAt(2) // returns 67:"C"

"ABC".charCodeAt(3) // returns NaN

3、codePointAt()

如果在指定的位置没有元素则返回undefined。如果在索引处开始没有 UTF-16 代理对,将直接返回在那个索引处的编码单元。

'ABC'.codePointAt(1);          // 66
'\uD800\uDC00'.codePointAt(0); // 65536
'XYZ'.codePointAt(42); // undefined

4、indexOf()

返回调用它的String对象中第一次出现的指定值的索引,从 fromIndex 处进行搜索。如果未找到该值,则返回 -1

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"

5、lastIndexOf()

返回调用String对象的指定值最后一次出现的索引,在一个字符串中的指定位置 fromIndex处从后向前搜索。如果没找到这个特定值则返回-1

'canal'.lastIndexOf('a');     // returns 3(没有指明 fromIndex 则从末尾 l 处开始反向检索到的第一个 a 出现在 l 的后面,即 index 为 3 的位置)
'canal'.lastIndexOf('a', 2);  // returns 1(指明 fromIndex 为 2 则从 n 处反向向回检索到其后面就是 a,即 index 为 1 的位置)
'canal'.lastIndexOf('a', 0);  // returns -1(指明 fromIndex 为 0 则从 c 处向左回向检索 a 发现没有,故返回-1)
'canal'.lastIndexOf('x');     // returns -1
'canal'.lastIndexOf('c', -5); // returns 0(指明 fromIndex 为-5 则视同 0,从 c 处向左回向查找发现自己就是,故返回 0)
'canal'.lastIndexOf('c', 0);  // returns 0(指明 fromIndex 为 0 则从 c 处向左回向查找 c 发现自己就是,故返回自己的索引 0)
'canal'.lastIndexOf('');      // returns 5
'canal'.lastIndexOf('', 2);   // returns 2

6、startsWith()

用来判断当前字符串是否以另外一个给定的子字符串开头,并根据判断结果返回 true 或 false

const str1 = 'Saturday night plans';

console.log(str1.startsWith('Sat'));
// expected output: true

console.log(str1.startsWith('Sat', 3));
// expected output: false

7、endsWith()

用来判断当前字符串是否是以另外一个给定的子字符串“结尾”的,根据判断结果返回 true 或 false

var str = "To be, or not to be, that is the question.";

alert( str.endsWith("question.") );  // true
alert( str.endsWith("to be") );      // false
alert( str.endsWith("to be", 19) );  // true

8、includes()

用于判断一个字符串是否包含在另一个字符串中,根据情况返回 true 或 false

var str = 'To be, or not to be, that is the question.';

console.log(str.includes('To be'));       // true
console.log(str.includes('question'));    // true
console.log(str.includes('nonexistent')); // false
console.log(str.includes('To be', 1));    // false
console.log(str.includes('TO BE'));       // false

总结一下:

上面介绍的8个方法,大致分为三类:

  • 字符串指定位置的字符或者字符编码:charAtcharCodeAtcodePointAt
  • 返回字符串中指定子串的位置或最后位置:indexOflastIndexOf
  • 字符串是否以指定字符串开始、结束或包含指定字符串:startsWithendsWithincludes

9、concat()

将一个或多个字符串与原字符串连接合并,形成一个新的字符串并返回。

let hello = 'Hello, '
console.log(hello.concat('Kevin', '. Have a nice day.'))
// Hello, Kevin. Have a nice day.

let greetList = ['Hello', ' ', 'Venkat', '!']
"".concat(...greetList)  // "Hello Venkat!"

"".concat({})    // [object Object]
"".concat([])    // ""
"".concat(null)  // "null"
"".concat(true)  // "true"
"".concat(4, 5)  // "45"

10、fromCharCode()

静态 String.fromCharCode() 方法返回由指定的 UTF-16 代码单元序列创建的字符串。

String.fromCharCode(65, 66, 67);   // 返回 "ABC"
String.fromCharCode(0x2014);       // 返回 "—"
String.fromCharCode(0x12014);      // 也是返回 "—"; 数字 1 被剔除并忽略
String.fromCharCode(8212);         // 也是返回 "—"; 8212 是 0x2014 的十进制表示

11、fromCodePoint()

String.fromCodePoint() 静态方法返回使用指定的代码点序列创建的字符串。

String.fromCodePoint(42);       // "*"
String.fromCodePoint(65, 90);   // "AZ"
String.fromCodePoint(0x404);    // "\u0404"
String.fromCodePoint(0x2F804);  // "\uD87E\uDC04"
String.fromCodePoint(194564);   // "\uD87E\uDC04"
String.fromCodePoint(0x1D306, 0x61, 0x1D307) // "\uD834\uDF06a\uD834\uDF07"

String.fromCodePoint('_');      // RangeError
String.fromCodePoint(Infinity); // RangeError
String.fromCodePoint(-1);       // RangeError
String.fromCodePoint(3.14);     // RangeError
String.fromCodePoint(3e-2);     // RangeError
String.fromCodePoint(NaN);      // RangeError

12、split()

使用指定的分隔符字符串将一个String对象分割成子字符串数组,以一个指定的分割字串来决定每个拆分的位置。

const str = 'The quick brown fox jumps over the lazy dog.';

const Words = str.split(' ');
console.log(words[3]);
// expected output: "fox"

const chars = str.split('');
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."]

13、slice()

提取某个字符串的一部分,并返回一个新的字符串,且不会改动原字符串

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"

14、substring()

返回一个字符串在开始索引到结束索引之间的一个子集,或从开始索引直到字符串的末尾的一个子集。

var anyString = "Mozilla";

// 输出 "Moz"
console.log(anyString.substring(0,3));
console.log(anyString.substring(3,0));
console.log(anyString.substring(3,-3));
console.log(anyString.substring(3,NaN));
console.log(anyString.substring(-2,3));
console.log(anyString.substring(NaN,3));

// 输出 "lla"
console.log(anyString.substring(4,7));
console.log(anyString.substring(7,4));

// 输出 ""
console.log(anyString.substring(4,4));

// 输出 "Mozill"
console.log(anyString.substring(0,6));

// 输出 "Mozilla"
console.log(anyString.substring(0,7));
console.log(anyString.substring(0,10));

15、substr()

返回一个字符串中从指定位置开始到指定字符数的字符(注意:该方法可能会被废弃,使用substring代替)

var str = "abcdefghij";

console.log("(1,2): "    + str.substr(1,2));   // (1,2): bc
console.log("(-3,2): "   + str.substr(-3,2));  // (-3,2): hi
console.log("(-3): "     + str.substr(-3));    // (-3): hij
console.log("(1): "      + str.substr(1));     // (1): bcdefghij
console.log("(-20, 2): " + str.substr(-20,2)); // (-20, 2): ab
console.log("(20, 2): "  + str.substr(20,2));  // (20, 2):

汇总一下:

  • concat:连接两个字符串并返回新的字符串。
  • fromCharCode, fromCodePoint:从指定的 Unicode 值序列构造一个字符串。这是一个 String 类方法,不是实例方法。
  • split:通过将字符串分离成一个个子串来把一个 String 对象分裂到一个字符串数组中。
  • slice:从一个字符串提取片段并作为新字符串返回。
  • substring, substr:分别通过指定起始和结束位置,起始位置和长度来返回字符串的指定子集。

16、match()

检索返回一个字符串匹配正则表达式的结果。

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"]

17、replace()

返回一个由替换值(replacement)替换部分或所有的模式(pattern)匹配项后的新字符串。模式可以是一个字符串或者一个正则表达式,替换值可以是一个字符串或者一个每次匹配都要调用的回调函数。如果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?"

18、search()

执行正则表达式和 String 对象之间的一个搜索匹配

var str = "hey JudE";
var re = /[A-Z]/g;
var re2 = /[.]/g;
console.log(str.search(re)); // returns 4, which is the index of the first capital letter "J"
console.log(str.search(re2)); // returns -1 cannot find '.' dot punctuation

19、toLowerCase()

会将调用该方法的字符串值转为小写形式,并返回。

console.log('中文简体 zh-CN || zh-Hans'.toLowerCase());
// 中文简体 zh-cn || zh-hans

console.log( "ALPHABET".toLowerCase() );
// "alphabet"

20、toUpperCase()

将调用该方法的字符串转为大写形式并返回(如果调用该方法的值不是字符串类型会被强制转换)。

const sentence = 'The quick brown fox jumps over the lazy dog.';

console.log(sentence.toUpperCase());
// expected output: "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG."

21、normalize()

会按照指定的一种 Unicode 正规形式将当前字符串正规化。(如果该值不是字符串,则首先将其转换为一个字符串)

const name1 = '\u0041\u006d\u00e9\u006c\u0069\u0065';
const name2 = '\u0041\u006d\u0065\u0301\u006c\u0069\u0065';

console.log(`${name1}, ${name2}`);
// expected output: "Amélie, Amélie"
console.log(name1 === name2);
// expected output: false
console.log(name1.length === name2.length);
// expected output: false

const name1NFC = name1.normalize('NFC');
const name2NFC = name2.normalize('NFC');
console.log(`${name1NFC}, ${name2NFC}`);
// expected output: "Amélie, Amélie"
console.log(name1NFC === name2NFC);
// expected output: true
console.log(name1NFC.length === name2NFC.length);
// expected output: true

22、repeat()

构造并返回一个新字符串,该字符串包含被连接在一起的指定数量的字符串的副本

"abc".repeat(-1)     // RangeError: repeat count must be positive and less than inifinity
"abc".repeat(0)      // ""
"abc".repeat(1)      // "abc"
"abc".repeat(2)      // "abcabc"
"abc".repeat(3.5)    // "abcabcabc" 参数 count 将会被自动转换成整数。
"abc".repeat(1/0)    // RangeError: repeat count must be positive and less than inifinity

({toString : () => "abc", repeat : String.prototype.repeat}).repeat(2)
//"abcabc",repeat 是一个通用方法,也就是它的调用者可以不是一个字符串对象。

23、trim()

会从一个字符串的两端删除空白字符。在这个上下文中的空白字符是所有的空白字符 (space, tab, no-break space 等) 以及所有行终止符字符(如 LF,CR 等)

var orig = '   foo  ';
console.log(orig.trim()); // 'foo'

// 另一个 .trim() 例子,只从一边删除

var orig = 'foo    ';
console.log(orig.trim()); // 'foo'

汇总一下:

  • match, replace, search:通过正则表达式来工作。
  • toLowerCase, toUpperCase:分别返回字符串的小写表示和大写表示。
  • normalize:按照指定的一种 Unicode 正规形式将当前字符串正规化。
  • repeat:将字符串内容重复指定次数后返回。
  • trim:去掉字符串开头和结尾的空白字符。

到此这篇关于梳理总结JavaScript的23个String方法的文章就介绍到这了,更多相关js String方法内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: 梳理总结JavaScript的23个String方法

本文链接: https://www.lsjlt.com/news/164322.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作