小白的常用字符串方法总结

347 阅读2分钟

//1.charAt() 返回在指定位置的字符。

var anyString = "Brave new world";

console.log("The character at index 0 is '" + anyString.charAt(0) + "'");

//The character at index 0 is 'B'

//2,charCodeAt() 返回在指定的位置的字符的 Unicode 编码。

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

const index = 4;

console.log(The character code ${sentence.charCodeAt(index)} is equal to ${sentence.charAt(index)});

// expected output: "The character code 113 is equal to q"

//3.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"]

//4.replace() 第一个参数为被匹配的值,第二个参数为被替换的值,对原字符串不改变,返回的是一个新的字符串

var p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';

var s = p.replace('dog', 'monkey');

console.log(s)

// expected output: "The quick brown fox jumps over the lazy monkey. If the dog reacted, was it really lazy?"

var regex = /Dog/ig;

var s = p.replace(regex, 'monkey');

console.log(s) // expected output: "The quick brown fox jumps over the lazy ferret. If the ferret reacted, was it really lazy?"

//5.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: "."

// 6.toLocaleLowerCase() 根据任何特定于语言环境的案例映射规则将被调用字串转换成小写格式的一个新字符串。返回值是一个新的字符串

'ALPHABET'.toLocaleLowerCase(); // 'alphabet'

// 7.toLocaleUpperCase() 把字符串转换为大写。如上 'alphabet'.toLocaleUpperCase(); // 'ALPHABET'

//8.substring() 提取字符串中两个指定的索引号之间的字符,返回一个新的字符串 var anyString = "Mozilla";

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

//9.substr()

console.log('findCommonPrefix'.substr(2,6)); //第一个参数从索引号开始提取,第二个参数的字符是提取的个数

console.log('findCommonPrefix'.substring(2,6)); // 从第一个参数开始提取到第二个参数为止,不包括第二个参数

// 9.trim()法会从一个字符串的两端删除空白字符。 // 返回值是一个代表调用字符串两端去掉空白的新字符串。 const greeting = ' Hello world! ';

console.log(greeting); // expected output: " Hello world! ";

console.log(greeting.trim()); // expected output: "Hello world!";