Js对象String常用属性、方法

143 阅读7分钟

String.length 字符串长度

空字符串的 length 为 0

var x = "Mozilla";
var empty = "";

console.log("Mozilla is " + x.length + " code units long");
/* "Mozilla is 7 code units long" */

console.log("The empty string is has a length of " + empty.length);
/* "The empty string is has a length of 0" */

charAt() 返回指定字符串

charAt() 方法从一个字符串中返回指定的字符。

语法:str.charAt(index)

index:一个介于0 和字符串长度减1之间的整数。 (0~length-1) 如果没有提供索引,charAt() 将使用0。

var anyString = "Brave new world";

console.log(anyString.charAt(0));    //输出:B
console.log(anyString.charAt(1));    //输出:r
console.log(anyString.charAt(2));    //输出:a
console.log(anyString.charAt(3));    //输出:v
console.log(anyString.charAt(4));    //输出:e
console.log(anyString.charAt(999));  //输出: 

str.charCodeAt()返回指定字符串UTF-16编码

str.charCodeAt(index)

返回的就是utf-16的字符编码

index:一个大于等于 0,小于字符串长度的整数。如果不是一个数值,则默认为 0。返回值指定 index 处字符的 UTF-16 代码单元值的一个数字;如果 index 超出范围,返回 NaN。

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

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

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

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

str.includes 是否包含的字符串

str.includes(searchString,[position])=>区分大小写

searchString:要在此字符串中搜索的字符串。

position:可选,从当前字符串的哪个索引位置开始搜寻子字符串,默认值为 0。 返回值

如果当前字符串包含被搜寻的字符串,就返回 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

indexOf() 返回是否包含的字符串的位置

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

str.indexOf(searchValue [, fromIndex]) =>区分大小写

searchValue:要被查找的字符串值。

如果没有提供确切地提供字符串,searchValue 会被强制设置为 "undefined", 然后在当前字符串中查找这个值。

举个例子:'undefined'.indexOf() 将会返回0,因为 undefined 在位置0处被找到,但是 'undefine'.indexOf() 将会返回 -1 ,因为字符串 'undefined' 未被找到。

fromIndex:可选,数字表示开始查找的位置。可以是任意整数,默认值为 0。

如果 fromIndex 的值小于 0,或者大于 str.length ,那么查找分别从 0 和str.length 开始。(译者注: fromIndex 的值小于 0,等同于为空情况; fromIndex 的值大于或等于 str.length ,那么结果会直接返回 -1 。)

举个例子,'hello world'.indexOf('o', -5) 返回 4 ,因为它是从位置0处开始查找,然后 o 在位置4处被找到。另一方面,'hello world'.indexOf('o', 11) (或 fromIndex 填入任何大于11的值)将会返回 -1 ,因为开始查找的位置11处,已经是这个字符串的结尾了。

"Blue Whale".indexOf("Blue")       // 返回 0
"Blue Whale".indexOf("Blute")      // 返回 -1
"Blue Whale".indexOf("Whale", 0)   // 返回 5
"Blue Whale".indexOf("Whale", 5)   // 返回 5
//若查找的为空就直接返回formIndex
"Blue Whale".indexOf("", -1)       // 返回 0
"Blue Whale".indexOf("", 9)        // 返回 9
"Blue Whale".indexOf("", 10)       // 返回 10
"Blue Whale".indexOf("", 11)       // 返回 10

substring()截取字符串

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

str.substring(indexStart[, indexEnd])[indexStart,indexEnd)不包括indexEnd

indexStart:需要截取的第一个字符的索引,该索引位置的字符作为返回的字符串的首字母。 indexEnd:可选。一个 0 到字符串长度之间的整数,以该数字为索引的字符不包含在截取的字符串内。 substring 提取从 indexStart 到 indexEnd(不包括)之间的字符。特别地:

  • 如果 indexStart 等于 indexEnd,substring 返回一个空字符串。
  • 如果省略 indexEnd,substring 提取字符一直到字符串末尾。
  • 如果任一参数小于 0 或为 NaN,则被当作 0。
  • 如果任一参数大于 stringName.length,则被当作 stringName.length。
  • 如果 indexStart 大于 indexEnd,则 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));

slice() 截取字符串

slice(beginIndex,endIndex) =>[beginIndex,endIndex)包括begin,不包括end(截取字符串)

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

beginIndex:从该索引(以0为基数)处开始提取原字符串中的字符。如果值为负数,会被当做 字符串的长度 + beginIndex 看待,(例如, 如果 beginIndex 是 -3 则看作是:strLength - 3)

endIndex:可选。在该索引(以 0 为基数)处结束提取字符串。如果省略该参数,slice() 会一直提取到字符串末尾。如果该参数为负数,则被看作是 strLength + endIndex,这里的 strLength 就是字符串的长度(例如,如果 endIndex 是 -3,则是, strLength - 3)。

var str1 = 'The morning is upon us.', // str1 的长度 length 是 23str2 = str1.slice(1, 8),
    str3 = str1.slice(4, -2),
    str4 = str1.slice(12),
    str5 = str1.slice(30);
console.log(str2); // 输出:he morn
console.log(str3); // 输出:morning is upon u
console.log(str4); // 输出:is upon us.
console.log(str5); // 输出:""

split()分割字符串

字符串转数组

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

str.split([separator:[, limit]])

separator:决定以什么拆分 limit:拆几个

var myString = "Hello World. How are you doing?";
var splits = myString.split(" ", 3);

console.log(splits);
//[ "Hello ", "1", " word. Sentence number ", "2", "." ]

arr.join 数组转字符串

var arr = ['a','b','c']
var str = arr.join('/')
console.log(str)

str.repeat() 重复字符串

str.repeat(count)

count:介于 0 和 +Infinity 之间的整数。表示在新构造的字符串中重复了多少遍原字符串。

重复次数不能为负数;必须小于 infinity,且长度不会大于最长的字符串。

"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()替换匹配的第一个

str.replace(regexp|substr, newSubStr|function)

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

replaceAll()替换全部

const newStr = str.replaceAll(regexp|substr, newSubstr|function)

replaceAll() 方法返回一个新字符串,新字符串所有满足 pattern 的部分都已被replacement 替换。pattern可以是一个字符串或一个 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/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?"

padStart() & padEnd() 填充字符串

str.padStart(targetLength [, padString])

str.padEnd(targetLength [, padString])

targetLength:目标长度
padString:填充字符串。
'abc'.padStart(10);         // "       abc"
'abc'.padStart(10, "foo");  // "foofoofabc"
'abc'.padStart(6,"123465"); // "123abc"
'abc'.padStart(8, "0");     // "00000abc"
'abc'.padStart(1);          // "abc"

'abc'.padEnd(10);          // "abc       "
'abc'.padEnd(10, "foo");   // "abcfoofoof"
'abc'.padEnd(6, "123456"); // "abc123"
'abc'.padEnd(1);           // "abc"

startsWith()字符串是否是开头

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

str.startsWith(searchString[, position])

searchString:给定的字符串
position:开始的位置
var str = "To be, or not to be, that is the question.";

alert(str.startsWith("To be"));         // true
alert(str.startsWith("not to be"));     // false
alert(str.startsWith("not to be", 10)); // true

trim()去除字符串两端空格

trimEnd()去除字符串结尾空格

trimStart去除字符串开头空格

toString()