简体   繁体   中英

Convert special character to string in javascript

Hi I have a vbscript function which replace the special character to string. I am replacing that function to javascript, but it is showing error. 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:

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. 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()

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)

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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