js簡單問題
var newvalue = value.replace(/[^\x00-\xff]/g, "** ");
是甚麼意思.
剛才查了下書,\xnn代表:由十六進制指定的拉丁字符...,不十很明白.
------解决方案--------------------var newvalue = value.replace(/[^\x00-\xff]/g, "** ");
的意思是把value对象(这里是字符串)里面不是\x00到\xff的字符全部替换为**,并把结果赋给
对象newvalue
------解决方案--------------------匹配单字节字符
一般都用[^\x00-\xff]来匹配汉字等双字节字符
你可以用下面的程序测试一下效果:
<html>
<head>
<meta http-equiv= "Content-Type " content= "text/html; charset=gb2312 ">
<title> HEX </title>
</head>
<body>
<script type= "text/javascript ">
var digitArray = new Array( '0 ', '1 ', '2 ', '3 ', '4 ', '5 ', '6 ', '7 ', '8 ', '9 ', 'a ', 'b ', 'c ', 'd ', 'e ', 'f ');
function toHex(n)
{
var result = ' '
var start = true;
for(var i=32;i> 0; )
{
i -= 4;
var digit = ( n > > i ) & 0xf;
if(!start || digit != 0)
{
start = false;
result += digitArray[digit];
}
}
return ( result == ' ' ? '0 ' : result );
}
function pad(str,len,pad)
{
var result = str;
for(var i=str.length;i <len;i++)
{
result = pad + result;
}
return '\\x ' + result;
}
function EncodeHex(value)
{
var str = value;
var result = " ";
for(var i=0;i <str.length;i++)
{
if( str.substring(i,i+1).match(/[^\x00-\xff]/g) != null )
{
result += escape(str.substring(i,i+1), 1).replace(/%/g, '\\ ');
}
else
{
result += pad(toHex(str.substring(i,i+1).charCodeAt(0)&0xff),2, '0 ');
}
}
return result;
}
</script>
<input type= "text " id= "t " value= " " /> <input type= "button " value= "转换成十六进制 " onclick= "alert(EncodeHex(document.getElementById( 't ').value)) " />
</body>
</html>
------解决方案--------------------(/[^\x00-\xff]/g
这里多用于计算字符串的长度,将所有双字节字符替换为两个**.
实例:
<script type= "text/javascript ">
var s= 'asbdfehr中国73824132我们 ';
alert( "[ "+s+ "]的长度: "+s.replace(/[^\x00-\xff]/gi, 'xx ').length)
</script>
------解决方案--------------------同意 jinjuduo() 的说法