返回 1.1
1.2
2.1
2.2
2.3
3.1
3.2
3.3
4.1
4.2
4.3
5.1
5.2
5.3
5.4
5.5
5.6
JS中字符串常用的操作方法集合
前端
2024-01-31 16:44:00
JS字符串操作方法大全
1. 增
这里的“增”并不是说直接增添内容,而是创建字符串的一个副本,再进行操作。除了常用 +
以及 ${}
进行字符串拼接之外,还可通过:
1.1 String.prototype.concat()
方法
const str1 = "Hello";
const str2 = "World";
const str3 = str1.concat(" ", str2); // "Hello World"
1.2 String.prototype.repeat()
方法
const str1 = "Hello";
const str2 = str1.repeat(3); // "HelloHelloHello"
2. 删
2.1 String.prototype.slice()
方法
const str = "Hello World";
const newStr = str.slice(6); // "World"
2.2 String.prototype.substring()
方法
const str = "Hello World";
const newStr = str.substring(6); // "World"
2.3 String.prototype.substr()
方法
const str = "Hello World";
const newStr = str.substr(6); // "World"
3. 改
3.1 String.prototype.replace()
方法
const str = "Hello World";
const newStr = str.replace("Hello", "Hi"); // "Hi World"
3.2 String.prototype.split()
方法
const str = "Hello World";
const arr = str.split(" "); // ["Hello", "World"]
3.3 String.prototype.trim()
方法
const str = " Hello World ";
const newStr = str.trim(); // "Hello World"
4. 查
4.1 String.prototype.indexOf()
方法
const str = "Hello World";
const index = str.indexOf("World"); // 6
4.2 String.prototype.lastIndexOf()
方法
const str = "Hello World World";
const index = str.lastIndexOf("World"); // 12
4.3 String.prototype.includes()
方法
const str = "Hello World";
const isIncluded = str.includes("World"); // true
5. 其他
5.1 String.prototype.toLowerCase()
方法
const str = "Hello World";
const newStr = str.toLowerCase(); // "hello world"
5.2 String.prototype.toUpperCase()
方法
const str = "Hello World";
const newStr = str.toUpperCase(); // "HELLO WORLD"
5.3 String.prototype.charAt()
方法
const str = "Hello World";
const char = str.charAt(0); // "H"
5.4 String.prototype.charCodeAt()
方法
const str = "Hello World";
const code = str.charCodeAt(0); // 72
5.5 String.prototype.fromCharCode()
方法
const code = 72;
const char = String.fromCharCode(code); // "H"
5.6 String.prototype.length
属性
const str = "Hello World";
const length = str.length; // 11
总结
以上是对JS中字符串常用操作方法的总结。希望本文对您有所帮助。