js字符串 常用方法 并带详细讲解

JavaScript中字符串是一种基本数据类型,表示文本数据。字符串常用方法有以下几种:

  1. length:返回字符串的长度。
let str = "hello world";
console.log(str.length); // 11
  1. indexOf:返回字符串中指定字符或子串的位置,如果不存在则返回-1。
let str = "hello world";
console.log(str.indexOf("o")); // 4
console.log(str.indexOf("z")); // -1
  1. slice:返回字符串中指定位置的子串。
let str = "hello world";
console.log(str.slice(0, 5)); // "hello"
console.log(str.slice(6)); // "world"
  1. substring:返回字符串中指定位置的子串,与slice方法类似,但不能接受负数参数。
let str = "hello world";
console.log(str.substring(0, 5)); // "hello"
console.log(str.substring(6)); // "world"
  1. substr:返回字符串中指定长度的子串,第二个参数表示子串的长度。
let str = "hello world";
console.log(str.substr(0, 5)); // "hello"
console.log(str.substr(6)); // "world"
  1. replace:替换字符串中的指定字符或子串。
let str = "hello world";
console.log(str.replace("world", "JavaScript")); // "hello JavaScript"
  1. toUpperCase:将字符串转换为大写。
let str = "hello world";
console.log(str.toUpperCase()); // "HELLO WORLD"
  1. toLowerCase:将字符串转换为小写。
let str = "HELLO WORLD";
console.log(str.toLowerCase()); // "hello world"
  1. trim:去除字符串两端的空格。
let str = "   hello world   ";
console.log(str.trim()); // "hello world"

以上是JavaScript中字符串常用方法的详细讲解及举例。

猜你喜欢

转载自blog.csdn.net/weixin_45506717/article/details/130402661
今日推荐