JavaScript学习笔记(1)字符串方法

字符串方法

  • length 属性返回字符串的长度
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length;
  • indexOf() 方法返回字符串中指定文本首次出现的索引(位置):
  • lastIndexOf() 方法返回指定文本在字符串中最后一次出现的索引:
  • 如果未找到文本, indexOf() 和 lastIndexOf() 均返回 -1。
var str = "The full name of China is the People's Republic of China.";
var pos = str.indexOf("China");

var str = "The full name of China is the People's Republic of China.";
var pos = str.lastIndexOf("China");
  • 两种方法都接受作为检索起始位置的第二个参数。
var str = "The full name of China is the People's Republic of China.";
var pos = str.indexOf("China", 18);

var str = "The full name of China is the People's Republic of China.";
var pos = str.lastIndexOf("China", 50);
  • search() 方法搜索特定值的字符串,并返回匹配的位置:
var str = "The full name of China is the People's Republic of China.";
var pos = str.search("locate");

提取部分字符串
有三种提取部分字符串的方法:

slice(start, end)
substring(start, end)
substr(start, length)

slice() 方法
slice() 提取字符串的某个部分并在新字符串中返回被提取的部分。
该方法设置两个参数:起始索引(开始位置),终止索引(结束位置)。
这个例子裁剪字符串中位置 7 到位置 13 的片段:

实例

var str = "Apple, Banana, Mango";
var res = str.slice(7,13);
res 的结果是:Banana

如果某个参数为负,则从字符串的结尾开始计数。
这个例子裁剪字符串中位置 -12 到位置 -6 的片段:

实例

var str = "Apple, Banana, Mango";
var res = str.slice(-13,-7);

如果省略第二个参数,则该方法将裁剪字符串的剩余部分:
实例
var res = str.slice(7);

或者从结尾计数:
实例
var res = str.slice(-13);
  • substring() 方法
    substring() 类似于 slice()。
    不同之处在于 substring() 无法接受负的索引。

  • substr() 方法
    substr() 类似于 slice()。
    不同之处在于第二个参数规定被提取部分的长度。

  • 替换字符串内容
    replace() 方法用另一个值替换在字符串中指定的值:

实例

str = "Please visit Microsoft!";
var n = str.replace("Microsoft", "W3School");

默认地,replace() 只替换首个匹配
默认地,replace() 对大小写敏感。

  • 转换为大写和小写
    通过 toUpperCase() 把字符串转换为大写:
    通过 toLowerCase() 把字符串转换为小写:
    实例
var text1 = "Hello World!";       // 字符串
var text2 = text1.toUpperCase();  // text2 是被转换为大写的 text1
  • concat() 方法
    concat() 连接两个或多个字符串:
    实例
    和+实际上是等效的
var text1 = "Hello";
var text2 = "World";
text3 = text1.concat(" ",text2);
  • String.trim()
    trim() 方法删除字符串两端的空白符:
var str = "       Hello World!        ";
alert(str.trim());

charAt() 方法
charAt() 方法返回字符串中指定下标(位置)的字符串:
charCodeAt() 方法
charCodeAt() 方法返回字符串中指定索引的字符 unicode 编码:

实例

var str = "HELLO WORLD";
str.charAt(0);            // 返回 H

var str = "HELLO WORLD";

str.charCodeAt(0);         // 返回 72

猜你喜欢

转载自blog.csdn.net/weixin_45551083/article/details/104062458