var stringOne = "Speak up, I can't hear you."; var stringTwo = stringOne.toLocaleUpperCase(); // "SPEAK UP, I CAN'T HEAR YOU" var stringThree = stringOne.toUpperCase(); // "SPEAK UP, I CAN'T HEAR YOU"
将字符串转换为小写:
var stringOne = "YOU DON'T HAVE TO YELL"; var stringTwo = stringOne.toLocaleLowerCase(); // "you don't have to yell" var stringThree = stringOne.toLowerCase(); // "you don't have to yell"
模式匹配
在一个字符串匹配的模式,可以使用两种方法,其基本的工作方式相同。
一个字符串match()方法被调用,并通过正则表达式:
var myString = "How much wood could a wood chuck chuck"; var myPattern = /.ood/; var myResult = myString.match(myPattern); // ["wood"] var patternLocation = myResult.index; // 9 var originalString = myResult.input // "How much wood could a wood chuck chuck"
exec()方法被调用的一个正则表达式对象,并通过字符串:
var myString = "How much wood could a wood chuck chuck"; var myPattern = /.huck/; var myResult = myPattern.exec(myString); // ["chuck"] var patternLocation = myResult.index; // 27 var originalString = myResult.input // "How much wood could a wood chuck chuck"
对于这两种方法,只在第一个匹配发生被返回。如果没有找到匹配,将返回空值。
也可以使用search()方法,它接受一个正则表达式作为唯一的参数,并返回模式第一次出现的位置:
var myString = "Assume"; var patternLocation = myString.search(/ume/); // 3
如果没有找到匹配,则该方法返回“-1”。
比较两个字符串的排序顺序
您可以比较两个字符串,看看哪一个字母先靠前使用localeCompare,,有三个可能的返回值:
var myString = "chicken"; var myStringTwo = "egg"; var whichCameFirst = myString.localeCompare(myStringTwo); // -1 (except Chrome, which returns -2) whichCameFirst = myString.localeCompare("chicken"); // 0 whichCameFirst = myString.localeCompare("apple"); // 1 (Chrome returns 2) stringObject.localeCompare(target)//公式
如上图所示,如果 stringObject 小于 target,则 localeCompare() 返回小于 0 的数。如果 stringObject 大于 target,则该方法返回大于 0 的数。如果两个字符串相等,或根据本地排序规则没有区别,该方法返回 0。
由于浏览器可以返回任何负数或正数之前和之后的结果最好使用 if ( result < 0 ) ,而不是if ( result === -1 ),后者将无法在Chrome浏览器中运行。