简体   繁体   English

在JavaScript中将特殊字符转换为字符串

[英]Convert special character to string in javascript

Hi I have a vbscript function which replace the special character to string. 嗨,我有一个vbscript函数,它将特殊字符替换为字符串。 I am replacing that function to javascript, but it is showing error. 我正在将该函数替换为javascript,但显示错误。 Below is the funciton 下面是功能

<script language="vbscript">
Function ReplaceSpecialChars(strValue)      
    if strValue <> "" then
        strValue=Replace(strValue,"\","\\")
        strValue=Replace(strValue,"[","\[")
        strValue=Replace(strValue,"]","\]")
        strValue=Replace(strValue,"*","\*")     
        strValue=Replace(strValue,"^","\^")
        strValue=Replace(strValue,"$","\$")
        strValue=Replace(strValue,".","\.")
        strValue=Replace(strValue,"|","\|")
        strValue=Replace(strValue,"?","\?")
        strValue=Replace(strValue,"+","\+")
        strValue=Replace(strValue,"(","\(")
        strValue=Replace(strValue,")","\)")
        strValue=Replace(strValue,"{","\{")
        strValue=Replace(strValue,"}","\}")
    end if  
     ReplaceSpecialChars=strValue
End Function

I converted this function to javascript function as below: 我将此函数转换为javascript函数,如下所示:

var replaceSpecialChars = function (strValue) {
if (strValue !== "") {
    strValue = strValue.replace("\'", "\\''");
    //strValue = strValue.replace(/\\/g, "\\\\"); 
    strValue = strValue.replace("[", "\[");
    strValue = strValue.replace("]", "\]");
    strValue = strValue.replace("*", "\*");
    strValue = strValue.replace("^", "\^");
    strValue = strValue.replace("$", "\$");
    strValue = strValue.replace(".", "\.");
    strValue = strValue.replace("|", "\|");
    strValue = strValue.replace("?", "\?");
    strValue = strValue.replace("+", "\+");
    strValue = strValue.replace("(", "\(");
    strValue = strValue.replace(")", "\)");
    strValue = strValue.replace("{", "\{");
    strValue = strValue.replace("}", "\}");
}
return strValue;

}; };

Which is being used by the following line: 以下行正在使用哪个:

var a = function(value) {
     var varC = "(?:^|\\s)(" + replaceSpecialChars(value) + ")(?=\\s|$)"
                    varRegExp = new RegExp(varC, "ig")
                    if (expression1.search(varRegExp) != -1) {
                        alert("Duplicate value not allowed in Record " + (i + 1));
                        return false;
                    };

But it is showing error. 但是它显示错误。

EDIT 编辑

That code you posted for the replaceSpecialChars function works (when you uncomment the line that replaces the '\\' character with '\\') for the first of each character. 您为replaceSpecialChars函数发布的代码适用于每个字符的第一个字符(当您取消注释将'\\'字符替换为'\\'的行时)。 I expect that the error is because your replaces weren't replacing ALL instances, so your regex had a bunch of special characters left over. 我希望该错误是因为您的替换未替换所有实例,所以您的正则表达式还剩下一堆特殊字符。


You'll want 你想要

String.prototype.replace() String.prototype.replace()

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/replace https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/replace

In order to make it replace all instances you will need a regular expression with the additional character 'g' (these initialisations are equivalent, but the second one is preferred) 为了使其替换所有实例,您将需要带有附加字符'g'的正则表达式(这些初始化是等效的,但是第二个是首选的)

var regex = new RegExp('pattern', 'g');
var betterRegex = /pattern/g;

The 'g' tells it to find all instances, otherwise it would stop at the first. 'g'告诉它找到所有实例,否则它将首先停止。

However, be careful with the second initialisation... 但是,请注意第二次初始化...

var regex = /\/g;

Is going to throw an error, because it won't be able to find the closing '/' symbol, since you told it to escape it. 将会引发错误,因为它不能找到结束的'/'符号,因为您告诉它转义了它。 What you want is: 您想要的是:

var regex = /\\/g;

Which tells it to look for the character '\\'. 告诉它寻找字符“ \\”。 Something similar happens for all of the other characters as well, so make sure you escape them all in your regex's. 其他所有字符也会发生类似的情况,因此请确保在正则表达式中将它们全部转义。

For a string, only the '\\' has to be escaped like that; 对于字符串,只需要像这样对'\\'进行转义; the other characters don't need. 其他字符不需要。

So, your function is going to look something like this... 因此,您的函数将看起来像这样...

function replaceSpecialChars(str) {
   var result;
   if (str !== "") {
      result = str.replace(/\\/g, '\\\\');
      result = str.replace(/\[/g, '\[');
      result = str.replace(/\]/g, '\]');
      result = str.replace(/\*/g, '\*');
      ...
   }
   return result; 
}

For the full list of characters that have special meaning in RegExp and what they do see... https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp (You actually have to work out the special characters from the descriptions, but you've already listed pretty much ALL of the special characters in a regex) 有关在RegExp中具有特殊含义的字符的完整列表以及它们的作用,请参阅... https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/RegExp (实际上,您必须从描述中找出特殊字符,但是您已经在正则表达式中列出了几乎所有特殊字符)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM