[基础类型巩固1]String

时间:2021-09-10 15:41:23
/**用了这么长时间的js,也该系统的学学基础类型的东西啦.~
* 环境:ECMAScript5.1;node 6.10.1
* Created by liyanq on 17/5/5.
* 教材来源:http://docs.sencha.com/extjs/6.2.1/modern/String.html
*/
/**String对象***********************************************************/
// 1,构造:String()是个全局的函数,用来构造对象,但不推荐这么用,可以用new Object("")替代
var s1 = new Object(" 1+2 ");//分配了内存空间,存在堆中
var s2 = " 2+2 ";//只是个常量值,存在栈中
console.log(typeof s1);//object
console.log(typeof s2);//string
console.log(s1.constructor == String);//true
console.log(eval(s1.valueOf()));//3
console.log(s1);//[String: ' 1+2 ']
//2,localeCompare,也可用用><替代.
console.log(s1.localeCompare(s2));//-1
//3,trim():返回字符串常量,并不改变自己的值.NOTE: This method is part of the ECMAScript 5 standard.
console.log(typeof (s1.trim()));//string,不是object
//4,toUpperCase,toLowerCase;都是返回字符串常量,并不改变自己的值.而且得注意函数名称大小写.
//5,substring ( indexA , [indexB] ) : String 文档写的太好了,直接贴了;注意返回字符串常量
/*Returns the characters in a string between two indexes into the string.
substring extracts characters from indexA up to but not including indexB(重点,不包括indexB).
In particular:
If indexA equals indexB, substring returns an empty string: indexA==indexB返回空
If indexB is omitted, substring extracts characters to the end of the string indexB忽略,返回后面全部
If either argument is less than 0 or is NaN, it is treated as if it were 0. 参数如果小于0或NaN,用做0;
If either argument is greater than stringName.length, it is treated as if it were stringName.length.
If indexA is larger than indexB, then the effect of substring is as if the two arguments were swapped;
for example, str.substring(1, 0) == str.substring(0, 1).(重点,小的数总是在前面)

利用它,写个替代的函数:*/
function replaceStr(str, oldStr, newStr) {
var r;
for (var i = 0; i < str.length; i++) {
if (str.substring(i, i + oldStr.length) == oldStr) {
r = str.substring(0, i) + newStr + str.substring(i + oldStr.length);
}
}
return r;
}
console.log(replaceStr("hello", "e", "E"));
//6,substr ( start , length ) : String;注意,后面参数是数量
/*参数解释:start is a character index. The index of the first character is 0,
and the index of the last character is 1 less than the length of the string.
0<=start<str.length
If start is positive and is greater than or equal to the length of the string, substr returns an empty string.
如果start为正数且大于或等于str.length,那么返回空字符串.
If start is negative, substr uses it as a character index from the end of the string.
如果start为负数,substr将从字符串的结尾算起.
If start is negative and abs(start) is larger than the length of the string, substr uses 0 as the start index.
如果start为负数且绝对值大于字符串长度,那么将用0代替start的值.
Note: the described handling of negative values of the start argument is not supported by Microsoft JScript.
注意:Microsoft JScript不支持start为负数情况.
If length is 0 or negative, substr returns an empty string.
如果长度参数是0或者负数,那么返回空字符串.
If length is omitted, substr extracts characters to the end of the string.
如果长度参数被忽略,返回至字符串结尾*/
//7,String split ( seperator , limit ) : Array
/*参数解释:seperator : String
Specifies the character to use for separating the string.
The separator is treated as a string or a regular expression.//字符串或正确的正则表达式
If separator is omitted, the array returned contains one element consisting of the entire string.
被忽略的话,返回只有一个整个字符串元素的数组.
limit : Number
Integer specifying a limit on the number of splits to be found.
The split method still splits on every match of separator,
but it truncates the returned array to at most limit elements.
虽然指定了数量限制的参数,split依然会分割全部匹配的分割符,但返回的数组的长度最多是限制的数量.
*/
//数量限制
var myString1 = "Hello World. How are you doing?";
console.log(myString1.split(" ", 3));//[ 'Hello', 'World.', 'How' ]
//正则形式
var myString2 = "Hello 1 word. Sentence number 2.";
console.log(myString2.split(/(\d)/));
//能去掉多余空格的没调试出来~~~~
var names = "Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand ";
var re = new RegExp("/\s*;/\s*\/");
console.log(names.split(re));

//8,slice ( beginSlice , endSlice ) : String;切片
//个人理解=substring,但注意的是,当beginSlice>endSlice的时候,结果为空.而substring会交换两参数
/*参数解释:
beginSlice : Number
The zero-based index at which to begin extraction.
endSlice : Number
The zero-based index at which to end extraction. If omitted, slice extracts to the end of the string.
*/
var str1 = "The morning is upon us.";
console.log(str1.slice(4,-2));//morning is upon u

//9,search ( regexp ) : Number
/*参数解释:
* regexp : RegExp
A regular expression object.
If a non-RegExp object obj is passed, it is implicitly converted to a RegExp by using new RegExp(obj).
说是能自动转换成正则对象
RETURNS :Number
If successful, search returns the index of the regular expression inside the string.
Otherwise, it returns -1.
*/

console.log("hello world".search(/(wor)/));//6

//10,charAt ( index ) : String
/*参数解释:
* index : Number
* An integer between 0 and 1 less than the length of the string.*/

//11,charCodeAt ( index ) : Number
/* PARAMETERS
index : Number
An integer greater than 0 and less than the length of the string;
if it is not a number, it defaults to 0.
RETURNS :Number
Returns a number indicating the Unicode value of the character at the given index.
Value between 0 and 65535.*/
console.log("北京".charCodeAt(0));//21271
//12,concat ( strings ) : String
console.log("北京".concat("欢迎","你"));//北京欢迎你
//13,fromCharCode ( numbers ) : String 属于类方法
console.log(String.fromCharCode(65,66,67,21271));//ABC北
//14,indexOf ( searchValue , fromIndex ) : Number
/*PARAMETERS
searchValue : String
A string representing the value to search for.
fromIndex : Number
The location within the calling string to start the search from.
It can be any integer between 0 and the length of the string.
The default value is 0.
RETURNS :Number
Position of specified value or -1 if not found.
*/
console.log("Blue Whale".indexOf("Blue"));//0.区分大小写
console.log("Blue Whale".indexOf(""));// returns 0 注意这个, 不是返回-1
console.log("Blue Whale".indexOf("",10));//returns 10 注意这个,不是返回-1
//15,lastIndexOf ( searchValue , fromIndex ) : Number
/*PARAMETERS
searchValue : String
A string representing the value to search for.
fromIndex : Number
The location within the calling string to start the search from, indexed from left to right.
It can be any integer between 0 and the length of the string.
The default value is the length of the string.*/
console.log("Blue Whale, Killer Whale".lastIndexOf("blue"));//-1 区分大小写
//16,localeCompare ( compareString ) : Number
/*PARAMETERS
compareString : String
The string against which the referring string is comparing.
RETURNS :Number
Returns -1 if the string occurs earlier in a sort than compareString,
returns 1 if the string occurs afterwards in such a sort,
and returns 0 if they occur at the same level.*/
//17,match ( regexp ) : Array
/*PARAMETERS
regexp : RegExp
A RegExp object. If a non-RegExp object obj is passed,
it is implicitly converted to a RegExp by using new RegExp(obj).
RETURNS :Array
Contains results of the match (if any).
该数组的内容依赖于 regexp 是否具有全局标志 g。

说明
match() 方法将检索字符串 stringObject,以找到一个或多个与 regexp 匹配的文本。这个方法的行为在很大程度上有赖于 regexp 是否具有标志 g。
如果 regexp 没有标志 g,那么 match() 方法就只能在 stringObject 中执行一次匹配。如果没有找到任何匹配的文本, match() 将返回 null。
否则,它将返回一个数组,其中存放了与它找到的匹配文本有关的信息。该数组的第 0 个元素存放的是匹配文本,而其余的元素存放的是与正则表达式的子表达式匹配的文本。
除了这些常规的数组元素之外,返回的数组还含有两个对象属性。index 属性声明的是匹配文本的起始字符在 stringObject 中的位置,input 属性声明的是对 stringObject 的引用。
如果 regexp 具有标志 g,则 match() 方法将执行全局检索,
找到 stringObject 中的所有匹配子字符串。若没有找到任何匹配的子串,则返回 null。
如果找到了一个或多个匹配子串,则返回一个数组。
不过全局匹配返回的数组的内容与前者大不相同,它的数组元素中存放的是 stringObject 中所有的匹配子串,而且也没有 index 属性或 input 属性。

注意:在全局检索模式下,match() 即不提供与子表达式匹配的文本的信息,也不声明每个匹配子串的位置。
如果您需要这些全局检索的信息,可以使用 RegExp.exec()*/
var str = "For more information, see Chapter 3.4.5.1";
var reMatch = /(chapter \d+(\.\d)*)/i;
console.log(str.match(reMatch));
/*[ 'Chapter 3.4.5.1',//数组的第 0 个元素存放的是匹配文本
'Chapter 3.4.5.1',//其余的元素存放的是与正则表达式的子表达式匹配的文本
'.1', //其余的元素存放的是与正则表达式的子表达式匹配的文本
index: 26,
input: 'For more information, see Chapter 3.4.5.1' ]

"Chapter 3.4.5.1" is the first match and the first value remembered from (Chapter \d+(\.\d)*).
".1" is the second value remembered from (\.\d).*/

//18,JavaScript replace() 方法
/*注意:
1,正则中默认区分大小写,加i修饰是不区分大小写.
2,正则中默认找第一个匹配的内容,加g匹配全部的内容.
3,$1、$2、...、$99,表示与 regexp 中的第 1 到第 99 个子表达式相匹配的文本。而/Microsoft/这个形式则用不了.
定义和用法
replace() 方法用于在字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的子串。
语法
stringObject.replace(regexp/substr,replacement)*/
console.log("Visit Microsoft!".replace(/Microsoft/,"W3School"));//Visit W3School!
console.log("Welcome to Microsoft!Welcome to Microsoft!".replace(/Microsoft/g,"W3School"));//Welcome to W3School!Welcome to W3School!
console.log("Javascript Tutorial".replace(/javascript/i,"javaScript"));//Javascript Tutorial
console.log("Doe hello, John".replace(/(\w+)\s*, \s*(\w+)/g,"$2,$1"));//Doe John,hello
console.log('"a", "b"'.replace(/"([^"]*)"/g, "{$1}"));//{a}, {b}
/*^ 表示待匹配串的开始位置
$ 表示待匹配串的结束位置
^在[]内时表示非*/

console.log("aaa bbb ccc".replace(/\b\w+\b/g,function (word) {
return word.substring(0,1).toUpperCase()+word.substring(1);
}));//Aaa Bbb Ccc
/*1、\b只能匹配字母、数字、汉字、下划线
2、\b就近匹配,比如\bAB 匹配A,AB\b 匹配B;
但如果只写一个\b或者在两个字母、数字、汉字、下划线之间有\b时就在所有字符或者两个字母、数字、汉字、下划线之间所有字符去逐个匹配

\b匹配的是字之间的看不见的边界,每个单词前后都有 \b
所以 \byes\b只能匹配 yes yes 而不能匹配 yesyes
*/

var myRegTest = new RegExp("a\\b.*h.*");
console.log(myRegTest.test("a,china"));