Js 字符串属性及方法
本文记录下字符串相关属性及方法,参考文档 MDM String。
一、语法:
‘hello world’
“hello world”
“中文”
“español”
"English "
“português”
“বাংলা”
“русский”
“日本語”
“ਪੰਜਾਬੀ”
“한국어”
String 全局对象是一个用于字符串或一个字符序列的构造函数,使用 String 函数将其他值生成或转换成字符串:
String(thing)
new String(thing)
模板字面量:
使用反引号包裹的字符串:
`hello world`
`hello ${who}`
转义字符:
除了普通的可打印字符以外,一些有特殊功能的字符可以通过转义字符的形式放入字符串中:
Code | Output |
---|---|
\0 | 空字符 |
’ | 单引号 |
" | 双引号 |
\ | 反斜杠 |
\n | 换行 |
\r | 回车 |
\v | 垂直制表符 |
\t | 水平制表符 |
\b | 退格 |
\f | 换页 |
\uXXXX | unicode 码 |
\u{X} … \u{XXXXXX} | unicode codepoint 实验性 |
\xXX | Latin-1 字符 (x 小写) |
长字符串:
有时,你的代码可能含有很长的字符串。你可能想将这样的字符串写成多行,而不是让这一行无限延长或着被编辑器折叠。有两种方法可以做到这一点。
其一,可以使用 + 运算符将多个字符串连接起来,如下所示:
let longString = "This is a very long string which needs " +
"to wrap across multiple lines because " +
"otherwise my code is unreadable. ";
其二,可以在每行末尾使用反斜杠字符(“\”),以指示字符串将在下一行继续。确保反斜杠后面没有空格或任何除换行符之外的字符或缩进; 否则反斜杠将不会工作。 如下所示:
let longString = “This is a very long string which needs \
to wrap across multiple lines because \
otherwise my code is unreadable.”;
使用这两种方式会创建相同的字符串。
二、描述:
从字符串中获取单个字符,有两种方式:
第一种是使用 charAt 方法:
return ‘cat’.charAt(1); // 输出:“a”
第二种是把字符串当作一个类似数组的对象,其中的每个字符对应一个数值索引:
return ‘cat’[1]; // 输出:“a”
字符串比较:
在 JavaScript 中,你只需要使用比较操作符 ( > ,< ,==,>= , <= ) ,就能进行字符串的比较。
let a=‘ab’
let b=‘ac’
let c= ‘ab’
console.log(a<b) // 输出:true
console.log(b<a) // 输出:false
console.log(a==c) // 输出:true
基本字符串和字符串对象的区别:
请注意区分 JavaScript 字符串对象和基本字符串值 。( 对于 Boolean 和Numbers 也同样如此)
字符串字面量 (通过单引号或双引号定义) 和 直接调用 String 方法 (没有通过 new 生成字符串对象实例) 的字符串都是基本字符串。JavaScript 会自动将基本字符串转换为字符串对象,只有将基本字符串转化为字符串对象之后才可以使用字符串对象的方法。当基本字符串需要调用一个字符串对象才有的方法或者查询值的时候 (基本字符串是没有这些方法的),JavaScript 会自动将基本字符串转化为字符串对象并且调用相应的方法或者执行查询。
var s_prim = “foo”;
var s_obj = new String(s_prim);
console.log(typeof s_prim); // 输出:“string”
console.log(typeof s_obj); // 输出:“object”
当使用 eval时,基本字符串和字符串对象也会产生不同的结果。eval 会将基本字符串作为源代码处理; 而字符串对象则被看作对象处理,返回对象。 例如:
s1 = “2 + 2”; // 创建一个 基本字符串
s2 = new String(“2 + 2”); // 创建一个 字符串对象
console.log(eval(s1)); // 输出:number 4
console.log(eval(s2)); // 输出:string “2 + 2”
三、属性:
String.length,表示一个字符串的长度。
四、方法:
at()
接受一个整数值,并返回一个新的 String。该方法允许正整数和负整数。负整数从字符串中的最后一个字符开始倒数。
语法:str.at(index)
const sentence = ‘The quick brown fox jumps over the lazy dog.’;
let index = 5;
console.log(sentence.at(index)); // 输出: “u”
index = -4;
console.log(sentence.at(index)); // 输出: “d”
charAt()
从一个字符串中返回指定的字符。字符串中的字符从左向右索引(0~length-1),如果指定的 index 值超出了该范围,则返回一个空字符串。
语法:str.charAt(index)
var anyString = “Brave new world”;
console.log(anyString.charAt(0)); // 输出: “u”
console.log(anyString.charAt(2)); // 输出: “a”
console.log(anyString.charAt(999)); // 输出: “ ”
charCodeAt()
返回 0 到 65535 之间的整数,表示给定索引处的 UTF-16 代码单元。
语法:str.charCodeAt(index)
const sentence = ‘The quick brown fox jumps over the lazy dog.’;
const index = 4;
console.log(sentence.charAt(index)); // 输出: “113”
codePointAt()
返回 一个 Unicode 编码点值的非负整数。返回值是在字符串中的给定索引的编码单元体现的数字,如果在索引处没找到元素则返回 undefined 。
语法:str.charCodeAt(index)
‘ABC’.codePointAt(1); // 66
‘\uD800\uDC00’.codePointAt(0); // 65536
‘XYZ’.codePointAt(42); // undefined
concat()
将一个或多个字符串与原字符串连接合并,形成一个新的字符串并返回。 concat 方法并不影响原字符串。
ps: 强烈建议使用赋值操作符 (en-US)(+, +=)代替 concat 方法。
语法:str.concat(str2, [, …strN])
let hello = 'Hello, '
console.log(hello.concat(‘Kevin’, ‘. Have a nice day.’))
// Hello, Kevin. Have a nice day.
endsWith()
用来判断当前字符串是否是以另外一个给定的子字符串“结尾”的,根据判断结果返回 true 或 false。
语法:str.concat(str2, [, …strN])
const str1 = ‘Cats are the best!’;
console.log(str1.endsWith(‘best!’));
// expected output: true
console.log(str1.endsWith(‘best’, 17));
// expected output: true
const str2 = ‘Is this a question?’;
console.log(str2.endsWith(‘question’));
// expected output: false
includes()
用于判断一个字符串是否包含在另一个字符串中,根据情况返回 true 或 false。
语法:str.includes(searchString[, position])
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
indexOf()
给定一个参数:要搜索的子字符串,搜索整个调用字符串,并返回指定子字符串第一次出现的索引。给定第二个参数:一个数字,该方法将返回指定子字符串在大于或等于指定数字的索引处的第一次出现。
语法:str.indexOf(searchString, position)
‘Blue Whale’.indexOf(‘Blue’) // 返回 0
‘Blue Whale’.indexOf(‘Blute’) // 返回 -1
‘Blue Whale’.indexOf(‘Whale’, 0) // 返回 5
‘Blue Whale’.indexOf(‘Whale’, 5) // 返回 5
‘Blue Whale’.indexOf(‘Whale’, 7) // 返回 -1
‘Blue Whale’.indexOf(‘’) // 返回 0
‘Blue Whale’.indexOf(‘’, 9) // 返回 9
‘Blue Whale’.indexOf(‘’, 10) // 返回 10
‘Blue Whale’.indexOf(‘’, 11) // 返回 10
lastIndexOf()
返回调用String 对象的指定值最后一次出现的索引,在一个字符串中的指定位置 fromIndex处从后向前搜索。如果没找到这个特定值则返回-1 。
语法:str.lastIndexOf(searchValue[, fromIndex])
“Blue Whale, Killer Whale”.lastIndexOf(“Kill”); // returns 12
“Blue Whale, Killer Whale”.lastIndexOf(“Kill”,11); // returns -1
“Blue Whale, Killer Whale”.lastIndexOf(“blue”); // returns -1
localeCompare()
返回一个数字来指示一个参考字符串是否在排序顺序前面或之后或与给定字符串相同。
语法:str.localeCompare(compareString[, locales[, options]])
‘a’.localeCompare(‘c’); // -2 or -1 (or some other negative value)
‘check’.localeCompare(‘against’); // 2 or 1 (or some other positive value)
‘a’.localeCompare(‘a’); // 0
match()
检索返回一个字符串匹配正则表达式的结果。
语法:str.match(regexp)
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”]
matchAll()
返回一个包含所有匹配正则表达式的结果及分组捕获组的迭代器。
语法:str.matchAll(regexp)
const regexp = /t(e)(st(\d?))/g;
const str = ‘test1test2’;
const array = […str.matchAll(regexp)];
console.log(array[0]);
// expected output: Array [“test1”, “e”, “st1”, “1”]
console.log(array[1]);
// expected output: Array [“test2”, “e”, “st2”, “2”]
normalize()
按照指定的一种 Unicode 正规形式将当前字符串规范化。(如果该值不是字符串,则首先将其转换为一个字符串)。
语法:str.normalize([form])
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
padEnd()
用一个字符串填充当前字符串(如果需要的话则重复填充),返回填充后达到指定长度的字符串。从当前字符串的末尾(右侧)开始填充。
语法:str.padEnd(targetLength, padString)
const str1 = ‘Breaded Mushrooms’;
console.log(str1.padEnd(25, ‘.’));
// expected output: “Breaded Mushrooms…”
const str2 = ‘200’;
console.log(str2.padEnd(5));
// expected output: "200 "
padStart()
用另一个字符串填充当前字符串(如果需要的话,会重复多次),以便产生的字符串达到给定的长度。从当前字符串的左侧开始填充。
语法:str.padStart(targetLength, padString)
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”
repeat()
构造并返回一个新字符串,该字符串包含被连接在一起的指定数量的字符串的副本。
语法:str.repeat(count)
“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 是一个通用方法,也就是它的调用者可以不是一个字符串对象。
replace()
返回一个由替换值(replacement)替换部分或所有的模式(pattern)匹配项后的新字符串。模式可以是一个字符串或者一个正则表达式,替换值可以是一个字符串或者一个每次匹配都要调用的回调函数。如果pattern是字符串,则仅替换第一个匹配项。原字符串不会改变。
语法:str.replace(regexp|substr, newSubStr|function)
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?”
replaceAll()
返回一个新字符串,新字符串所有满足 pattern 的部分都已被replacement 替换。pattern可以是一个字符串或一个 RegExp, replacement可以是一个字符串或一个在每次匹配被调用的函数。原始字符串保持不变。
语法:str.replaceAll(regexp|substr, newSubstr|function)
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/ig;
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?”
search()
执行正则表达式和 String 对象之间的一个搜索匹配。
语法:str.search(regexp)
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
slice()
提取某个字符串的一部分,并返回一个新的字符串,且不会改动原字符串。
语法:str.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”
split()
使用指定的分隔符字符串将一个String对象分割成子字符串数组,以一个指定的分割字串来决定每个拆分的位置。
语法:str.split([separator[, limit]])
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.”]
startsWith()
用来判断当前字符串是否以另外一个给定的子字符串开头,并根据判断结果返回 true 或 false。
语法:str.startsWith(searchString[, position])
const str1 = ‘Saturday night plans’;
console.log(str1.startsWith(‘Sat’));
// expected output: true
console.log(str1.startsWith(‘Sat’, 3));
// expected output: false
substring()
返回一个字符串在开始索引到结束索引之间的一个子集,或从开始索引直到字符串的末尾的一个子集。
语法:str.substring(indexStart[, indexEnd])
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));
toLocaleLowerCase()
根据任何指定区域语言环境设置的大小写映射,返回调用字符串被转换为小写的格式。
语法:
str.toLocaleLowerCase()
str.toLocaleLowerCase(locale)
str.toLocaleLowerCase([locale, locale, …])
‘ALPHABET’.toLocaleLowerCase(); // ‘alphabet’
‘\u0130’.toLocaleLowerCase(‘tr’) === ‘i’; // true
‘\u0130’.toLocaleLowerCase(‘en-US’) === ‘i’; // false
let locales = [‘tr’, ‘TR’, ‘tr-TR’, ‘tr-u-co-search’, ‘tr-x-turkish’];
‘\u0130’.toLocaleLowerCase(locales) === ‘i’; // true
toLocaleLowerCase()
根据本地主机语言环境把字符串转换为大写格式,并返回转换后的字符串。
语法:
str.toLocaleUpperCase()
str.toLocaleUpperCase(locale)
str.toLocaleUpperCase([locale, locale, …])
const city = ‘istanbul’;
console.log(city.toLocaleUpperCase(‘en-US’));
// expected output: “ISTANBUL”
console.log(city.toLocaleUpperCase(‘TR’));
// expected output: “İSTANBUL”
toLowerCase()
将调用该方法的字符串值转为小写形式,并返回。
语法:str.toLowerCase()
console.log(‘中文简体 zh-CN || zh-Hans’.toLowerCase());
// 中文简体 zh-cn || zh-hans
console.log( “ALPHABET”.toLowerCase() );
// “alphabet”
toUpperCase()
将调用该方法的字符串转为大写形式并返回。
语法:str.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.”
toString()
字符串对象的 toString() 方法返回一个字符串,表示指定的字符串。
语法:str.toString()
const stringObj = new String(‘foo’);
console.log(stringObj);
// expected output: String { “foo” }
console.log(stringObj.toString());
// expected output: “foo”
trim()
从一个字符串的两端删除空白字符。在这个上下文中的空白字符是所有的空白字符 (space, tab, no-break space 等) 以及所有行终止符字符(如 LF,CR 等)。
语法:str.trim()
const greeting = ’ Hello world! ';
console.log(greeting);
// expected output: " Hello world! ";
console.log(greeting.trim());
// expected output: “Hello world!”;
trimEnd() / trimRight()
trimEnd() 方法从一个字符串的末端移除空白字符。trimRight() 是这个方法的别名。
语法:str.trimEnd(); str.trimRight();
const greeting = ’ Hello world! ';
console.log(greeting);
// expected output: " Hello world! “;
console.log(greeting.trimEnd());
// expected output: " Hello world!”;
trimStart() / trimLeft()
trimStart() 方法从字符串的开头删除空格。trimLeft() 是此方法的别名。
语法:str.trimStart(); str.trimLeft();
const greeting = ’ Hello world! ';
console.log(greeting);
// expected output: " Hello world! ";
console.log(greeting.trimStart());
// expected output: "Hello world! ";
valueOf()
字符串对象的 toString() 方法返回一个字符串,表示指定的字符串。
语法:str.valueOf()
const stringObj = new String(‘foo’);
console.log(stringObj);
// expected output: String { “foo” }
console.log(stringObj.valueOf());
// expected output: “foo”