fix/escape javascript escape character? - javascript

see this answer for reasoning why / is escaped and what happens on nonspecial characters
I have a string that looks like this after parsing. This string comes fron a javascript line.
var="http:\/\/www.site.com\/user"
I grabbed the inside of the quote so all i have is http:\/\/www.site.com\/user. How do i properly escape the string? so its http://www.site.com/user? I am using .NET

Use the String.Replace() method:
string expr = #"http:\/\/www.site.com\/user"; // That's what you have.
expr = expr.Replace("\\/", "/"); // That's what you want.
That, or:
expr = expr.Replace(#"\/", "/");
Note that the above doesn't replace occurrences of \ with the empty string, just in case you have to support strings that contain other, legitimate backslashes. If you don't, you can write:
expr = expr.Replace("\\", "");
Or, if you prefer constants to literals:
expr = expr.Replace("\\", String.Empty);

I am not sure why it has the \ in it since var foo = "http://www.site.com/user"; is a valid string.
If the \ characters are meant to be there for some strange reason, than you need to double them up
var foo = "http:\\/\\/www.site.com\\/user";

Related

Wrong result when replacing with regex

I'm replacing a sub-string using replace function and regex expression.
However after character escape and replacement, I still have an extra '/' character. I'm not really familiar with regex can someone guide me.
I have implemented the escape character function found here: Is there a RegExp.escape function in Javascript?
RegExp.escape= function(s) {
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
};
const latexConversions = [
["\\cdot", "*"],
["\\right\)", ")"],
["\\left\(", "("],
["\\pi", "pi"],
["\\ln\((.*?)\)", "log($1)"],
["stdev\((.*?)\)", "std($1)"],
["stdevp\((.*?)\)", "std(\[$1\], \"uncorrected\")"],
["mean\((.*?)\)", "mean($1)"],
["\\sqrt\((.*?)\)", "sqrt($1)"],
["\\log\((.*?)\)", "log10($1)"],
["\(e\)", "e"],
["\\exp\((.*?)\)", "exp($1)"],
["round\((.*?)\)", "round($1)"],
["npr\((.*?),(.*?)\)", "($1!/($1-$2)!)"],
["ncr\((.*?),(.*?)\)", "($1!/($2!($1-$2)!))"],
["\\left\|", "abs("],
["\\right\|", ")"],
];
RegExp.escape = function (s) {
var t = s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
return t;
};
mathematicalExpression = "\\sqrt( )"
//Problem is here
mathematicalExpression = mathematicalExpression.replace(new RegExp(RegExp.escape(latexConversions[8][0]), 'g'), latexConversions[8][1]);
//Works
mathematicalExpression2 = mathematicalExpression.replace(/\\sqrt\((.*?)\)/g, "sqrt($1)");
alert("what I got: "+mathematicalExpression); // "\sqrt()"
alert("Supposed to be: "+ mathematicalExpression2); // "sqtr()"
I have a live example here: https://jsfiddle.net/nky342h5/2/
There are several misconceptions regarding the string literal "\\sqrt\((.*?)\)":
This string in raw characters is: \sqrt((.*?)). Note how there is no difference between the two opening parentheses: the backslash in the string literal was not very useful. In other words, "\(" === "("
Both opening parentheses will be escaped by RegExp.escape
Points 1 and 2 are equally true for the closing parentheses, for the dot, the asterisk and the question mark: they will be escaped by RegExp.escape.
In short, you have no way to distinguish that a character is intended as a literal or as a regex special symbol -- you are escaping all of them as if they were intended as literal characters.
The solution:
Since you already are encoding regex specific syntax in your strings (like (.*?)), you might as well use regex literals instead of string literals.
In the case you highlighted, instead of this:
["\\sqrt\((.*?)\)", "sqrt($1)"]
...use this:
[/\\sqrt\((.*?)\)/g, "sqrt($1)"]
And let your code do:
mathematicalExpression = mathematicalExpression.replace(...latexConversions[8]);
Alternative
If for some reason regex literals are a no-go, then define your own special syntax for (.*?). For instance, use the symbol µ to denote that particular regex syntax.
Then your array pair would look like this:
["\\sqrt(µ)", "sqrt($1)"],
...and code:
mathematicalExpression = mathematicalExpression.replace(
new RegExp(RegExp.escape(latexConversions[8][0]).replace(/µ/g, '(.*?)'), 'g'),
latexConversions[8][1]
);
Note how here the (.*?) is introduced in the string after RegExp.escape has done its job.
extra \ rather than escaping everything
replace ["\\sqrt\((.*?)\)", "sqrt($1)"], with ["\\\\sqrt\((.*?)\)", "sqrt($1)"],
and replace the final replace with
mathematicalExpression = mathematicalExpression.replace(new RegExp((latexConversions1[8][0]), 'g'), latexConversions1[8][1]);

Match double quotes that doesn't have a preceding escape character

I have a string that has some double quotes escaped and some not escaped.
Like this,
var a = "abcd\\\"\""
a = a.replace(/\[^\\\]\"/g, 'bcde')
console.log(a)
The string translates to literal, abcd\"".
Now, i am using the above regex to replace non-escaped double quotes.
And only the second double quote must be replaced.
The result must look like this,
abcd\"bcde
But it is returing the same original string, abcd\"" with no replacement.
You can use capture group here:
a = a.replace(/(^|[^\\])"/g, '$1bcde')
//=> abcd\"bcde
A negative lookbehind is what you want. However it is not supported in the Regex' JS flavor.
You can achieve this by processing the result in two steps:
var a = "abcd\\\"\"";
console.log(a);
var result = a.replace(/(\\)?"/g, function($0,$1){ return $1?$0:'{REMOVED}';});
console.log(result);

Replace single backslash "\" with double backslashes "\\"

I have string with file path. I want to replace all single backslashes ("\") with double backslashes ("\\").
var replaceableString = "c:\asd\flkj\klsd\ffjkl";
var part = /#"\\"/g;
var filePath = replaceableString .replace(part, /#"\\"/);
console.log(filePath);
Console showed me it.
c:asdlkjklsdfjkl
I found something like this, unfortunately it didn't work.
Replacing \ with \\
Try:
var parts = replaceableString.split('\\');
var output = parts.join('\\\\');
Personally, as I am not so expert in reg exps, I tend to avoid them when dealing with non-alphanumeric characters, both due to readability and to avoid weird mistake.
var replaceableString = "c:\asd\flkj\klsd\ffjkl";
alert(replaceableString);
This will alert you c:asdlkjklsdfjkl because '\' is an escape character which will not be considered.
To have a backslash in your string , you should do something like this..
var replaceableString = "c:\\asd\\flkj\\klsd\\ffjkl";
alert(replaceableString);
This will alert you c:\asd\flkj\klsd\ffjkl
JS Fiddle
Learn about Escape sequences here
If you want your string to have '\' by default , you should escape it .. Use escape() function
var replaceableString = escape("c:\asd\flkj\klsd\ffjkl");
alert(replaceableString);
JS Fiddle
You have several problems in your code.
To get a \ in your string variable you need to escape it.
When you create a string like this: replaceableString = "c:\asd\flkj\klsd\ffjkl"; characters with a \ before are treated as escape sequences. So during the string creation, it tries to interpret the escape sequence \a, since this is not valid it stores the a to the string. E.g. \n would have been interpreted as newline.
I assume the # is coming from a .net example. Javascript does not know "raw" strings.
remove the quotes from your regex.
This would do what you want:
var string = "c:\\asd\\flkj\\klsd\\ffjkl";
var regex = /\\/g;
var FilePath = string.replace(regex, "\\\\");
Here is the answer:
For replacing single backslash with single forward slash:
var stringReplaced = String.raw`c:\asd\flkj\klsd\ffjkl`.split('\\').join('/')
console.log(stringReplaced);
For replacing double backslash with single forward slash:
var stringReplaced = String.raw`c:\\asd\\flkj\\klsd\\ffjkl`.split('\\\\').join('/')
console.log(stringReplaced);
\ is a escape character. Therefore replaceableString does not contain any backslashes.
To fix this you should declare the string like this:
var replaceableString = "c:\\asd\\flkj\\klsd\\ffjkl";
First encode the string
then replace all occurrences of %5C with %5C%5C
At the end decode the string
var result = encodeURI(input);
result=decodeURI(result.replace(/%5C/g,"%5C%5C"));
If you have no control over the contents of the string you are trying to find backslashes in, and it contains SINGLE \ values (eg. variable myPath contains C:\Some\Folder\file.jpg), then you can actually reference the single backslashes in JavaScript as String.fromCharCode(92).
So to get the file name in my filepath example above.
var justTheName = myPath.split(String.fromCharCode(92)).pop();
In case of string matching, it is better to use encodeURIComponent, decodeURIComponent.
match(encodeURIComponent(inputString));
function match(input)
{
for(i=0; i<arr.length; i++)
{
if(arr[i] == decodeURIComponent(input))
return true;
else return false;
}
}
In the case of a single back slash in the string, the javascript replace method did not allow me to replace the single back slash.
Instead I had to use the split method which returns an array of the split strings and then concatenate the strings without the back slash (or whatever you want to replace it with)
Solution (replaced backslash with underscore):
var splitText = stringWithBackslash.split('\\');
var updatedText = splitText[0] + '_' + splitText[1];
You need to pass to pass value of a string through String.raw before you assign value to a variable.
var replaceableString = String.raw`c:\asd\flkj\klsd\ffjkl`.replace(/\\/g,"\\\\");
console.log(replaceableString)

Replace Characters from string with javascript

I have a string like (which is a shared path)
\\cnyc12p20005c\mkt$\\XYZ\
I need to replace all \\ with single slash so that I can display it in textbox. Since it's a shared path the starting \\ should not be removed. All others can be removed.
How can I achieve this in JavaScript?
You could do it like this:
var newStr = str.replace(/(.)\\{2}/, "$1\\");
Or this, if you don't like having boobs in your code:
var newStr = "\\" + str.split(/\\{1,2}/).join("\\");
You can use regular expression to achieve this:
var s = '\\\\cnyc12p20005c\\mkt$\\\\XYZ\\';
console.log(s.replace(/.\\\\/g, '\\')); //will output \\cnyc12p20005c\mkt$\XYZ\
Double backslashes are used because backslash is special character and need to be escaped.

Exact replace of string in Javascript

hidValue="javaScript:java";
replaceStr = "java";
resultStr=hidValue.replace("/\b"+replaceStr+"\b/gi","");
resultStr still contains "javaScript:java"
The above code is not replacing the exact string java. But when I change the code and directly pass the value 'java' it's getting replaced correctly i.e
hidValue="javaScript:java";
resultStr=hidValue.replace(/\bjava\b/gi,"");
resultStr contains "javaScript:"
So how should I pass a variable to replace function such that only the exact match is replaced.
The replace-function does not take a string as first argument but a RegExp-object. You may not mix those two up. To create a RexExp-object out of a combined string, use the appropriate constructor:
resultStr=hidValue.replace(new RegExp("\\b"+replaceStr+"\\b","gi"),"");
Note the double backslashes: You want a backslash in your Regular Expression, but a backslash also serves as escape character in the string, so you'll have to double it.
Notice that in one case you're passing a regular expression literal /\bjava\b/gi, and in the other you're passing a string "/\bjava\b/gi". When using a string as the pattern, String.replace will look for that string, it will not treat the pattern as a regular expression.
If you need to make a regular expression using variables, do it like so:
new RegExp("\\b" + replaceStr + "\\b", "gi")
See:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace
`let msisdn = '5093240556699'
let isdnWith = numb.msisdn.slice(8,11);
let msisdnNew = msisdn.replace(isdnWith, 'XXX', 'gi');
show 5093240556XXX`

Categories