javascript技巧

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript技巧 > JS字符串常用属性方法

JavaScript字符串常用属性方法汇总及详解

作者:走粥

在JavaScript中,字符串是一个非常重要的数据类型,这篇文章主要介绍了JavaScript字符串常用属性方法汇总及详解的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参考下

方法分类汇总索引

  1. 获取字符串信息方法
  1. 字符串查找方法
  1. 字符串截取/提取方法
  1. 字符串转换方法
  1. 字符串替换/分割方法
  1. 字符串修剪方法
  1. 字符串重复方法
  1. 字符串连接方法
  1. 字符串填充方法
  1. 其他字符串方法

以下为 JavaScript 中常用的字符串方法详解,这些方法都不会改变原字符串,而是返回一个新的字符串或其他类型的值。

一、获取字符串信息属性

1. length

const str = "Hello World";
// 获取字符串长度
const len = str.length;
console.log(len); // 输出: 11
// 注意:length是属性,不是函数,不需要加括号

二、字符串查找方法

1. charAt()

const str = "JavaScript";
// 获取索引为4的字符
const char = str.charAt(4);
console.log(char); // 输出: 'S'

// 获取索引超出范围的字符(返回空字符串)
const invalidChar = str.charAt(20);
console.log(invalidChar); // 输出: ''

2. charCodeAt()

const str = "A";
// 获取字符 'A' 的 Unicode 编码
const code = str.charCodeAt(0);
console.log(code); // 输出: 65

// 获取索引超出范围的字符编码(返回NaN)
const invalidCode = str.charCodeAt(1);
console.log(invalidCode); // 输出: NaN

3. indexOf()

const str = "Hello, Hello World";
// 查找 "Hello" 首次出现的位置
const firstPos = str.indexOf("Hello");
console.log(firstPos); // 输出: 0

// 从索引5开始查找 "Hello"
const posFrom5 = str.indexOf("Hello", 5);
console.log(posFrom5); // 输出: 7

// 查找不存在的子字符串
const notFound = str.indexOf("JavaScript");
console.log(notFound); // 输出: -1

4. lastIndexOf()

const str = "Hello, Hello World";
// 查找 "Hello" 最后出现的位置
const lastPos = str.lastIndexOf("Hello");
console.log(lastPos); // 输出: 7

// 在索引6之前查找 "Hello"
const posBefore6 = str.lastIndexOf("Hello", 6);
console.log(posBefore6); // 输出: 0

5. includes()

const str = "Hello World";
// 判断字符串是否包含 "World"
const hasWorld = str.includes("World");
console.log(hasWorld); // 输出: true

// 从索引6开始查找 "World"
const hasWorldFrom6 = str.includes("World", 6);
console.log(hasWorldFrom6); // 输出: true

// 判断字符串是否包含 "Java"
const hasJava = str.includes("Java");
console.log(hasJava); // 输出: false

6. startsWith()

const str = "Hello World";
// 判断字符串是否以 "Hello" 开头
const startsWithHello = str.startsWith("Hello");
console.log(startsWithHello); // 输出: true

// 判断从索引6开始的子字符串是否以 "W" 开头
const startsWithW = str.startsWith("W", 6);
console.log(startsWithW); // 输出: true

// 判断字符串是否以 "World" 开头
const startsWithWorld = str.startsWith("World");
console.log(startsWithWorld); // 输出: false

7. endsWith()

const str = "Hello World";
// 判断字符串是否以 "World" 结尾
const endsWithWorld = str.endsWith("World");
console.log(endsWithWorld); // 输出: true

// 只考虑前5个字符,判断是否以 "Hello" 结尾
const endsWithHello = str.endsWith("Hello", 5);
console.log(endsWithHello); // 输出: true

// 判断字符串是否以 "Hello" 结尾
const endsWithHelloFull = str.endsWith("Hello");
console.log(endsWithHelloFull); // 输出: false

三、字符串截取/提取方法

1. slice()

const str = "Hello World";
// 提取从索引6开始到结束的子字符串
const world = str.slice(6);
console.log(world); // 输出: "World"

// 提取从索引0到5的子字符串(不包含索引5)
const hello = str.slice(0, 5);
console.log(hello); // 输出: "Hello"

// 使用负数索引(从字符串末尾开始计算)
const last3 = str.slice(-3);
console.log(last3); // 输出: "rld"

2. substring()

const str = "Hello World";
// 提取从索引0到5的子字符串
const hello = str.substring(0, 5);
console.log(hello); // 输出: "Hello"

// 如果startIndex大于endIndex,会自动交换它们
const swapped = str.substring(5, 0);
console.log(swapped); // 输出: "Hello"

// 负数索引会被视为0
const negative = str.substring(-3, 5);
console.log(negative); // 输出: "Hello"

3. substr()

const str = "Hello World";
// 从索引6开始提取5个字符
const world = str.substr(6, 5);
console.log(world); // 输出: "World"

// 从索引0开始提取5个字符
const hello = str.substr(0, 5);
console.log(hello); // 输出: "Hello"

// 使用负数作为起始索引(从末尾开始计算)
const last3 = str.substr(-3);
console.log(last3); // 输出: "rld"

四、字符串转换方法

1. toLowerCase()

const str = "Hello World";
// 将字符串转换为小写
const lowerStr = str.toLowerCase();
console.log(lowerStr); // 输出: "hello world"
console.log(str); // 输出: "Hello World"(原字符串未改变)

2. toUpperCase()

const str = "Hello World";
// 将字符串转换为大写
const upperStr = str.toUpperCase();
console.log(upperStr); // 输出: "HELLO WORLD"
console.log(str); // 输出: "Hello World"(原字符串未改变)

3. toString()

const str = "Hello";
// 返回字符串本身
const sameStr = str.toString();
console.log(sameStr); // 输出: "Hello"

// 对于String对象特别有用
const strObj = new String("World");
console.log(typeof strObj); // 输出: "object"
const strVal = strObj.toString();
console.log(typeof strVal); // 输出: "string"

4. valueOf()

// 对于字符串字面量,与原字符串相同
const str = "Hello";
console.log(str.valueOf()); // 输出: "Hello"

// 对于String对象,返回其原始值
const strObj = new String("World");
console.log(strObj.valueOf()); // 输出: "World"
console.log(typeof strObj.valueOf()); // 输出: "string"

五、字符串替换/分割方法

1. replace()

const str = "Hello World, Hello JavaScript";

// 替换第一个匹配的子字符串
const replacedOnce = str.replace("Hello", "Hi");
console.log(replacedOnce); // 输出: "Hi World, Hello JavaScript"

// 使用正则表达式替换所有匹配项(g表示全局匹配)
const replacedAll = str.replace(/Hello/g, "Hi");
console.log(replacedAll); // 输出: "Hi World, Hi JavaScript"

// 使用函数作为替换值
const replacedWithFunc = str.replace(/Hello/g, (match) => {
  return match.toUpperCase();
});
console.log(replacedWithFunc); // 输出: "HELLO World, HELLO JavaScript"

2. split()

const str = "apple,banana,orange,grape";

// 使用逗号作为分隔符
const fruits = str.split(",");
console.log(fruits); // 输出: ["apple", "banana", "orange", "grape"]

// 限制返回的数组长度为2
const limitedFruits = str.split(",", 2);
console.log(limitedFruits); // 输出: ["apple", "banana"]

// 使用空字符串作为分隔符,将每个字符作为数组元素
const chars = "hello".split("");
console.log(chars); // 输出: ["h", "e", "l", "l", "o"]

六、字符串修剪方法

1. trim()

const str = "   Hello World   ";
// 去除两端空白
const trimmed = str.trim();
console.log(trimmed); // 输出: "Hello World"
console.log(trimmed.length); // 输出: 11(原长度为17)

2. trimStart() / trimLeft()

const str = "   Hello World   ";
// 去除左侧空白
const trimmedStart = str.trimStart();
console.log(trimmedStart); // 输出: "Hello World   "
console.log(trimmedStart.length); // 输出: 14(原长度为17)

// trimLeft是trimStart的别名
const trimmedLeft = str.trimLeft();
console.log(trimmedLeft); // 输出: "Hello World   "

3. trimEnd() / trimRight()

const str = "   Hello World   ";
// 去除右侧空白
const trimmedEnd = str.trimEnd();
console.log(trimmedEnd); // 输出: "   Hello World"
console.log(trimmedEnd.length); // 输出: 14(原长度为17)

// trimRight是trimEnd的别名
const trimmedRight = str.trimRight();
console.log(trimmedRight); // 输出: "   Hello World"

七、字符串重复方法

1. repeat()

const str = "Hi";
// 重复3次
const repeated = str.repeat(3);
console.log(repeated); // 输出: "HiHiHi"

// 重复0次,返回空字符串
const empty = str.repeat(0);
console.log(empty); // 输出: ""

// 重复次数为负数会报错
try {
  str.repeat(-1);
} catch (e) {
  console.log(e); // 输出: RangeError: Invalid count value
}

八、字符串连接方法

1. concat()

const str1 = "Hello";
const str2 = " ";
const str3 = "World";

// 连接多个字符串
const result = str1.concat(str2, str3, "!");
console.log(result); // 输出: "Hello World!"

// 与使用 + 运算符效果相同
const sameResult = str1 + str2 + str3 + "!";
console.log(sameResult); // 输出: "Hello World!"

九、字符串填充方法

1. padStart()

const str = "5";
// 填充到长度为3,使用默认空格填充
const padded = str.padStart(3);
console.log(padded); // 输出: "  5"

// 填充到长度为5,使用"0"填充
const zeroPadded = str.padStart(5, "0");
console.log(zeroPadded); // 输出: "00005"

// 如果目标长度小于原字符串长度,则返回原字符串
const shorter = str.padStart(1);
console.log(shorter); // 输出: "5"

2. padEnd()

const str = "5";
// 填充到长度为3,使用默认空格填充
const padded = str.padEnd(3);
console.log(padded); // 输出: "5  "

// 填充到长度为5,使用"0"填充
const zeroPadded = str.padEnd(5, "0");
console.log(zeroPadded); // 输出: "50000"

// 使用多个字符进行填充
const multiChar = "Hi".padEnd(7, "abc");
console.log(multiChar); // 输出: "Hiabcab"(循环使用填充字符串)

十、其他字符串方法

1. match()

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

// 查找所有以字母"o"开头的单词
const matches = str.match(/o\w+/g);
console.log(matches); // 输出: ["ox", "over", "og"]

// 查找第一个匹配项的详细信息
const firstMatch = str.match(/q\w+/);
console.log(firstMatch); 
// 输出: ["quick", index: 4, input: "The quick brown fox jumps over the lazy dog", groups: undefined]

// 没有找到匹配项
const noMatch = str.match(/z\w+/);
console.log(noMatch); // 输出: null

2. matchAll()

const str = "Hello 123, Hello 456";
const regex = /Hello (\d+)/g;

// 获取所有匹配结果的迭代器
const matches = str.matchAll(regex);

// 将迭代器转换为数组
const results = Array.from(matches);
console.log(results);
// 输出: [
//   ["Hello 123", "123", index: 0, input: "Hello 123, Hello 456", groups: undefined],
//   ["Hello 456", "456", index: 11, input: "Hello 123, Hello 456", groups: undefined]
// ]

3. search()

const str = "Hello World";
// 查找第一个大写字母的位置
const upperPos = str.search(/[A-Z]/);
console.log(upperPos); // 输出: 0

// 查找"World"的位置
const worldPos = str.search(/World/);
console.log(worldPos); // 输出: 6

// 查找不存在的模式
const noPos = str.search(/Java/);
console.log(noPos); // 输出: -1

4. localeCompare()

const str1 = "apple";
const str2 = "banana";

// 比较两个字符串
console.log(str1.localeCompare(str2)); // 输出: -1("apple" 在 "banana" 之前)
console.log(str2.localeCompare(str1)); // 输出: 1("banana" 在 "apple" 之后)
console.log(str1.localeCompare("apple")); // 输出: 0(相等)

// 考虑地区的比较(德语中 "ä" 被视为 "a" 的变音)
console.log("ä".localeCompare("z", "de")); // 输出: -1
console.log("ä".localeCompare("z", "sv")); // 输出: 1(在瑞典语中 "ä" 排在 "z" 之后)

总结 

到此这篇关于JavaScript字符串常用属性方法汇总及详解的文章就介绍到这了,更多相关JS字符串常用属性方法内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文