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

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)

Related

splitting of strings in javascript which involves backslash

How can we split the following tag to extract the substring "PDSGJ:IO.HJ".
var input = "\\initvalues\PDSGJ:IO.HJ~some" .
I tried the following:
var input = "\\initvalues\PDSGJ:IO.HJ~some";
var b = input.split('\\');
alert(b[1]);
Note: The format remains the same , \\,\, ~ format is same and mandatory for all strings .
But the problem is , I get the output as: initvaluesPDSGJ:IO.HJ~some.
I need '\' also because I need to further split and get the value.
Any other method is there to get the value?
You can use regular expressions:
var input = '\\initvalues\PDSGJ:IO.HJ~some',
b = input.match(/[A-Z]+:[A-Z]+.[A-Z]+~[a-z]+/);
console.log(b && b[0]);
The backslash is interpreted as an escape character. So you're gonna have to add another backslash for each backslash.
Then directly search for the last backslash and then slice the string:
var input = "\\\\initvalues\\PDSGJ:IO.HJ~some";
var index = input.lastIndexOf('\\');
var str = input.slice(index+1)
alert(str);
It is indeed correct, like the others already mentioned, that a backslash is interpreted as an escape character.
To output proper result, thus as a list.
var txt='\\\\initvalues\\PDSGJ:IO.HJ~some';
txt.split(/\\\\/).pop(0).split(/\\/)
(2) ["initvalues", "PDSGJ:IO.HJ~some"]

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);

How to remove the special characters from a string using javascript

I have the below String value to be displayed in text area and i want to remove the first characters ##*n|n from the string .
The string is as follows :
Symbol-001
##*n|nClaimant Name
##*n|nTransaction
I have used the below code to deal with removing the special characters
var paramVal1 = parent.noteText; //paramVal1 will have the string now
var pattern = /[##*n|n]/g;
var paramVal1 = paramVal1.replace(pattern,'');
document.getElementById("txtNoteArea").value = paramval1;//appending the refined string to text area
For the above used code am getting the out put string as below
Symbol-001
|Claimat Name //here 'n' is missing and i have an extra '|' character
|Transactio //'n' is missing here too and an extra '|' character
Kindly help to remove the characters ##*n|n without affecting the other values
What your regex is saying is "remove any of the following characters: #|*n". Clearly this isn't what you want!
Try this instead: /##\*n\|n/g
This says "remove the literal string ##*n|n". The backslashes remove the special meaning from * and |.
You are using regular expression reserved chars in your pattern, you need to escape them
You can use this expression:
var pattern = /[\#\#\*n\|n]/g;
i think use this /[##*n\|n]/g regEx
If you want to replace the first occurrence as you say on your question, you don't need to use regex. A simple string will do, as long as you escape the asterisk:
var str = "Symbol-001 ##*n|nClaimant Name ##*n|nTransaction";
var str2 = str.replace("##\*n|n", ""); //output: "Symbol-001 Claimant Name ##*n|nTransaction"
If you want to replace all the occurrences, you can use regex, escaping all the characters that have a special meaning:
var str3 = str.replace(/\#\#\*n\|n/g, ""); //output: "Symbol-001 Claimant Name Transaction"
Have a look at this regex builder, might come in handy - http://gskinner.com/RegExr/

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.

fix/escape javascript escape character?

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";

Categories