为JavaScript的String增加Trim函数


Leader提出要求说要在JavaScript的输入规则检测之前先对字符串进行trim处理,我说好吧。

  于是开始立即动手写了一段JavaScript代码实现tirm函数:

String.prototype.trim = function(){
var i;
//先检测字符串右端的全、半角空格
for(i=this.length-1;i>=0;i--){
if(this.charAt(i)!=" "&&this.charAt(i)!=" ")
 break;
}
//获得去掉右端全、半角空格后的字符串
this=this.substring(0,i+1);
//再检测字符串右端的全、半角空格
for(i=0;i<this.length;i++){
if(this.charAt(i)!=" "&&this.charAt(i)!=" ")
 break;
}
//返回trim后的字符串
return this.substring(i,this.length);
}

  用起来没有什么问题,但是那代码怎么看怎么不爽————感觉两个枯燥的for循环就是碍眼和多余!代码怎么才能精简呢?又想起了可爱的正则表达式,这也是字符串的规则问题嘛!有了想法问题就好解决了。没有什么技术含量,也就不啰啰嗦嗦地进行分析了,直接给出用正则表达式实现的JS代码(后来发现竟然和官方给的一个例子一模一样,哈哈,巧了):

String.prototype.trim  =  function(){ 
 return  this.replace(/(^s*)|(s*$)/g,""); 
}

  简单说明一下:

  s 匹配任何空白字符,包括空格、制表符、换页符等等。等价于 [ fnrtv]。 ^s*的话就是匹配任何空白字符了,只要找到空白字符

  S 匹配任何非空白字符。等价于 [^ fnrtv]。

  $ 匹配输入字符串的结尾位置。如果设置了 RegExp 对象的 Multiline 属性,则 $ 也匹配 'n' 或 'r'。要匹配 $ 字符本身,请使用 $
/g 表示该表达式将用来在输入字符串中查找尽可能多的匹配。

  给段测试的代码:

<%@ page language="java" contentType="text/html; charset=SHIFT_JIS" %>
<%@ include file="/jsp/common/common_page.jsp" %>
<!DOCTYPE HTML PUBLIC "-//w3C//DTD HTML 4.01 Transitional//EN">
<script language="JavaScript" type="text/JavaScript">
String.prototype.trim = function() {
return this.replace(/(^s*)|(s*$)/g, "");
}
function tip(){
var tipMessage = document.getElementById("test").value;
alert("A" + tipMessage.trim() + "B");
}
</script>
<HTML lang="ja">
<title>
test
</title>
<body>
<input type="text" name = "test" style="width:100px">
<input type="button" onclick="tip()" value="submit">
</body>
</html>

  再一次显示了正则表达式的威力所在。一方面,代码的可读性提高了(当然你必须懂正则表达式);一方面,代码得到了最大的浓缩。

  顺便再给出几个String经常要用到的函数(网上转载):

// 去掉字符左端的的空白字符
String.prototype.leftTrim = function(){
  return this.replace(/(^[s]*)/g, "");
}
// 去掉字符右端的空白字符
String.prototype.rightTrim = function(){
  return this.replace(/([s]*$)/g, "");
}
// 返回字符的长度,一个中文算2个
String.prototype.chineseLength=function(){
  return this.replace(/[^x00-xff]/g,"**").length;
// 判断字符串是否以指定的字符串结束
String.prototype.endsWith = function(str) {
  return this.substr(this.length - str.length) == str;
}
// 判断字符串是否以指定的字符串开始
String.prototype.startsWith = function(str) {
  return this.substr(0, str.length) == str;

虽然 JavaScript 有很多用处,但是处理字符串是其中最流行的一个。下面让我们深入地分析一下使用 JavaScript 操作字符串。在 JavaScript 中, String 是对象。 String 对象并不是以字符数组的方式存储的,所以我们必须使用内建函数来操纵它们的值。这些内建函数提供了不同的方法来访问字符串变量的内容。下面我们详细看一下这些函数。

  包罗万象

  操作字符串的值是一般的开发人员必须面临的家常便饭。操作字符串的具体方式有很多,比如说从一个字符串是提取出一部分内容来,或者确定一个字符串是否包含一个特定的字符。下面的 JavaScript 函数为开发人员提供了他们所需要的所有功能:

  ? 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 使用这些函数。下面的代码是用到了前面提到的所有函数:

1 function manipulateString(passedString1, passedString2)
{ 2 3 var concatString; 
4 5 // The string passed to concat is added to the end of the first string 6 7 concatString = passedString1.concat(passedString2); 
8 9 alert(concatString);
10 11 // The following if statement will be true since first word is Tony 12 13
if (concatString.charAt(3) == "y")
{ 14 15 alert("Character found!");
16 17
}
18 19 // The last position of the letter n is 10 20 21 alert("The last index of n is: " + concatString.lastIndexOf("n"));
22 23 // A regular expression is used to locate and replace the substring 24 25 var newString = concatString.replace(/Tony/gi,"General");
26 27 // The following yields Please salute General Patton 28 29 alert("Please salute " + newString);
30 31 // The match function returns an array containing all matches found 32 33 matchArray = concatString.match(/Tony/gi);
34 35 for (var i=0; i<matchArray.length;i++)
{ 36 37 alert("Match found: " + matchArray[i]);
38 39
}
40 41 // Determine if the regular expression is found, a –1 indicates no 42 43 if (newString.search(/Tony/) == -1)
{ 44 45 alert("String not found");
46 47
}
else { 48 49 alert("String found.");
50 51 } 52 53 // Extract a portion of the string and store it in a new variable 54 55 var sliceString = newString.slice(newString.indexOf("l")+2,newString.length);
56 57 alert(sliceString);
58 59 // The split function creates a new array containing each value separated by a space 60 61 stringArray = concatString.split(" ");
62 63 for (var i=0; i<stringArray.length;i++)
{ 64 65 alert(stringArray[i]; 66 67 }
68 69 alert(newString.toUpperCase());
70 71 alert(newString.toLowerCase());
72 73
}
  }


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3