在Js中判斷某一變量是否為空時,如檢驗登錄信息的用戶名,密碼等,需要去掉空格,其中包括去掉右,左空格,還包括去掉所有空格,Js實現(xiàn)如下:
1
<script>
2
function doclick(){
3
var tt = " 1234 fdsef ";
4
String.prototype.Trim = function()
5
{
6
return this.replace(/(^\s*) |(\s*$)/g, ""); //去掉左右空格
7
8
}
9
10
String.prototype.LTrim = function()
11
{
12
return this.replace(/(^\s*)/g, ""); // 去掉左空格
13
14
}
15
16
String.prototype.RTrim = function()
17
{
18
return this.replace(/(\s*$)/g, ""); //去掉右空格
19
20
}
21
22
String.prototype.TrimAll = function()
23
{
24
return this.replace(/\s+/g,""); //去掉所有空格
25
26
}
27
28
alert(tt.Trim());
29
alert(tt.LTrim());
30
alert(tt.RTrim());
31
alert(tt.TrimAll());
32
</script>

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32
