JavaScript中Stringd对象方法总结

    技术2022-05-11  63

    •  concat() – 将两个或多个字符的文本组合起来,返回一个新的字符串。

    •  indexOf() – 返回字符串中一个子串第一处出现的索引。如果没有匹配项,返回 -1 。

    •  charAT() – 返回指定位置的字符。

    •  lastIndexOf() – 返回字符串中一个子串最后一处出现的索引,如果没有匹配项,返回 -1 。

    •  match() – 检查一个字符串是否匹配一个正则表达式。

    •  substring() – 返回字符串的一个子串。传入参数是起始位置和结束位置。

    •  replace() – 用来查找匹配一个正则表达式的字符串,然后使用新字符串代替匹配的字符串。

    •  search() – 执行一个正则表达式匹配查找。如果查找成功,返回字符串中匹配的索引值。否则返回 -1 。

    •  slice() – 提取字符串的一部分,并返回一个新字符串。

    •  split() – 通过将字符串划分成子串,将一个字符串做成一个字符串数组。

    •  length() – 返回字符串的长度,所谓字符串的长度是指其包含的字符的个数。

    •  toLowerCase() – 将整个字符串转成小写字母。

    •  toUpperCase() – 将整个字符串转成大写字母。

    注意: concat 、 match 、 replace 和 search 函数是在 JavaScript 1.2 中加入的。所有其它函数在 JavaScript 1.0 就已经提供了。

    下面让我们看一下如何在 JavaScript 使用这些函数。下面的代码是用到了前面提到的所有函数:

     

    function  manipulateString(passedString1, passedString2) {  var  concatString;  //  The string passed to concat is added to the end of the first string  concatString  =  passedString1.concat(passedString2); alert(concatString);  //  The following if statement will be true since first word is Tony  if  (concatString.charAt( 3 ==   " y " ) { alert( " Character found! " ); }  //  The last position of the letter n is 10  alert( " The last index of n is:  "   +  concatString.lastIndexOf( " n " ));  //  A regular expression is used to locate and replace the substring  var  newString  =  concatString.replace( / Tony / gi, " General " );  //  The following yields Please salute General Patton  alert( " Please salute  "   +  newString);  //  The match function returns an array containing all matches found  matchArray  =  concatString.match( / Tony / gi);  for  ( var  i = 0 ; i < matchArray.length;i ++ ) { alert( " Match found:  "   +  matchArray[i]); }  //  Determine if the regular expression is found, a –1 indicates no  if  (newString.search( / Tony / ==   - 1 ) { alert( " String not found " ); }  else  { alert( " String found. " ); }  //  Extract a portion of the string and store it in a new variable  var  sliceString  =  newString.slice(newString.indexOf( " l " ) + 2 ,newString.length); alert(sliceString);  //  The split function creates a new array containing each value separated by a space  stringArray  =  concatString.split( "   " );  for  ( var  i = 0 ; i < stringArray.length;i ++ ) { alert(stringArray[i]; } alert(newString.toUpperCase()); alert(newString.toLowerCase()); } 

     

    下面是执行上面的代码得到的结果:

    Tony Patton Character Found! The last index of n is: 10 Match found: Tony Please salute General Patton String not found Patton Tony Patton GENERAL PATTON general patton

    示例代码把所有这些提到的函数都用到了。


    最新回复(0)