字符串的基础
1.字符串的表示''
或""
包含的
var answer = "It's alright";
var answer = "He is called 'Johnny'";
var answer = 'He is called "Johnny"';
2.字符串的长度length
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length;
3.字符串中常用的转义字符\
var x = 'It\'s alright'; //It's alright
var y = "We are the so-called \"Vikings\" from the north." //We are the so-called "Vikings" from the north.
4.字符串的拼接+
与concat()
var text = "Hello" + " " + "World!"; //Hello World!
var text = "Hello".concat(" ", "World!"); //Hello World!
5.字符串string
转换为对象object
var x = "John";
var y = new String("John");
// typeof x will return string
// typeof y will return object
不要使用这种string创建object,它会使代码执行速度变慢,使代码更复杂化。
字符串的方法
1.返回指定索引区间的子串substring(start,end)
与slice()
类似,但不能取负值
var s = 'hello, world'
s.substring(0, 5); // 从索引0开始到5(不包括5),返回hello
s.substring(7); // 从索引7开始到结束,返回world
s.slice(-5) ; //从d:-1开始到w:-5,返回hello
2.返回指定长度区间的子串substr(start,length)
与slice()
类似,但不能取负值
var s = 'hello, world'
s.substr(0,5); //从索引0开始截取的长度为5,返回hello
3.内容的替换replace()
str = "Please visit Microsoft!";
var n = str.replace("Microsoft", "W3Schools"); //Please visit W3Schools
4.要替换不区分大小写的,请使用带i
标志(不敏感)的正则表达式
str = "Please visit Microsoft!";
var n = str.replace(/MICROSOFT/i, "W3Schools"); //Please visit W3Schools
5.若要替换所有匹配项,请使用一个正则表达式g
(全局匹配)
str = "Please visit Microsoft and Microsoft!";
var n = str.replace(/Microsoft/g, "W3Schools"); //Please visit W3Schools and W3Schools
6.把一个字符串全部变为大写toUpperCase()
var s = 'Hello';
s.toUpperCase(); // 返回HELLO
7.把一个字符串全部变为小写toLowerCase()
var s = 'Hello';
var lower = s.toLowerCase(); // 返回'hello'并赋值给变量lower
lower; // 'hello'
8.字符串的查找arr[]
与charAt()
var str = "HELLO WORLD";
str[0]; // returns H
var str = "HELLO WORLD";
str.charAt(0); // returns H