js 如何比较2个中文字符串是否相等

JavaScript022

js 如何比较2个中文字符串是否相等,第1张

js里面比较中文字符串实际是比较中文字符串的unicode编码值!

第一个汉字的unicode编码是:19968    表示汉字“一”;

最后一个汉字的unicode编码是:40869    标识汉字“龥”(yu,四声);

开始和结束之间的unicode代码区间是计算机能打出来的所有汉字。

比较的话可以直接用运算符比较,例如:

var a="一"

var b="龥"

a>b //false

a<b //true

a==b //false

a===b //false

//但是不能用“-”号,用“-”号js会尝试强转a变量的值为number,如果不能转成功会显示NaN,

//NaN 加减乘除结果都是NaN

//用“+”,js会优先执行拼接字符得到

a+b  // "一龥"

实际计算机内部执行比较是有类似如下操作的:

var a="一"

var b="龥"

a.charCodeAt(0)>b.charCodeAt(0) // false

JavaScript中replace() 方法如果直接用str.replace("-","!") 只会替换第一个匹配的字符.

而str.replace(/\-/g,"!")则可以全部替换掉匹配的字符(g为全局标志)。

replace()

The replace() method returns the string that results when you replace text matching its first argument

(a regular expression) with the text of the second argument (a string).

If the g (global) flag is not set in the regular expression declaration, this method replaces only the first

occurrence of the pattern. For example,

var s = "Hello. Regexps are fun." s = s.replace(/\./, "!" )// replace first period with an exclamation pointalert(s)

produces the string “Hello! Regexps are fun.” Including the g flag will cause the interpreter to

perform a global replace, finding and replacing every matching substring. For example,

var s = "Hello. Regexps are fun." s = s.replace(/\./g, "!" )// replace all periods with exclamation pointsalert(s)

yields this result: “Hello! Regexps are fun!”

所以可以用以下几种方式.:

string.replace(/reallyDo/g, replaceWith)

string.replace(new RegExp(reallyDo, 'g'), replaceWith)

string:字符串表达式包含要替代的子字符串。

reallyDo:被搜索的子字符串。

replaceWith:用于替换的子字符串。

Js代码

<script type="text/javascript">

String.prototype.replaceAll = function(reallyDo, replaceWith, ignoreCase) {

if (!RegExp.prototype.isPrototypeOf(reallyDo)) {

return this.replace(new RegExp(reallyDo, (ignoreCase ? "gi": "g")), replaceWith)

} else {

return this.replace(reallyDo, replaceWith)

}

}

</script>