JS基础类型

字符串方法:

  length:返回字符串的长度

var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length;

  indexOf():返回字符串中指定文本首次出现的索引位置;

var str = "The full name of China is the People's Republic of China.";
var pos = str.indexOf("China");

  lastIndexOf():返回指定文本在字符串中最后一次出现的位置的索引

var str = "The full name of China is the People's Republic of China.";
var pos = str.lastIndexOf("China");

  如果在indexOf和lastIndexOf中都没有找到文本,就会直接返回-1,其中都接受作为检索起始位置的第二个参数

var str = "The full name of China is the People's Republic of China.";
var pos = str.indexOf("China", 18); // 从位置为18的字符开始检索

  lastIndexOf()向后检索(从尾到头),假如第二个参数是50,就从50的位置开始检索,一直到字符串的起点。

var str = "The full name of China is the People's Republic of China.";
undefined
console.log(str.length)
VM1861:1 57
undefined
console.log(str.lastIndexOf('China', 50))
VM1984:1 17

  search():搜索特定的字符串,返回对应的匹配的值

  indexOf和search方法之间的区别:

    1、search是无法设置第二个开始位置参数的

    2、indexOf无法设置更强大的搜索值(正则表达式)

    

提取部分字符串:

  slice(start, end):提取字符串某个部分的新字符串中返回被提取的部分,,两个参数起始索引(开始位置), 终止索引(结束位置)

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

    如果省略了终止索引那么就会裁剪字符串的剩余部分

    负值位置不适用 Internet Explorer 8 及其更早版本。

  substring(start, end):功能类似于slice,但是不同之处是它无法接受负数索引

  substr(start, length):功能类似slice,不同之处是第二个参数规定被提取部分的长度, 省略第二个参数那就会裁减字符串所有的剩余部分,其中第二个参数不能是负数,因为这个是用来定义长度的

var str = "Apple, Banana, Mango";
var res = str.substr(7,6); // 从索引为7的位置开始选择6个字符

  

  replace():用另一个值替换在字符串中指定的值, 这个方法不会改变调用它的字符串,返回的是一个新的字符串,默认地,replace只会替换首个匹配,它对大小写敏感

    如需执行大小写不敏感的替换,请使用正则表达式 /i(大小写不敏感)

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

  toUpperCase():把字符串转换为大写

  toLowerCase():把字符串转换为小写

  concat():连接两个或者多个字符串

var text1 = "Hello";
var text2 = "World";
text3 = text1.concat(" ",text2);

    concat方法可用于代替加运算符。下面两行效果是等效的

var text = "Hello" + " " + "World!";
var text = "Hello".concat(" ","World!");

  所有的字符串方法都会返回新的字符串,它们不会修改原始的字符串,准确的说:字符串是不可改变的:字符串不能更改,只能替换

  

  string.trim():删除字符串两端的空白符

提取字符串字符:

  charAt(position):返回字符串中指定下标(位置)的字符串;

  charCodeAt(position):返回字符串中指定索引的字符的Unicode编码

var str = "HELLO WORLD";
str.charCodeAt(0);         // 返回 72

  split():将字符串转换为数组

var txt = "a,b,c,d,e";   // 字符串
txt.split(",");          // 用逗号分隔
txt.split(" ");          // 用空格分隔
txt.split("|");          // 用竖线分隔

  

数字方法:

  

  

原文地址:https://www.cnblogs.com/tulintao/p/13329268.html