how to replace \ with \\ using javascript string functions - javascript

I have the following filepath
var imagepath="C:\Documents and Settings\Mahesh\Desktop\images\advts.png"
how can I replace \ with \ so so that it prints
var imagepath="C:\\Documents and Settings\\Mahesh\\Desktop\\images\\advts.png"

You need to use the replace() method whilst escaping the \ character on each occurrence:
imagepath = imagepath.replace(/\\/g, "\\\\");
//-> "C:\\Documents and Settings\\Mahesh\\Desktop\\images\\advts.png"
If imagepath is defined with single backslash characters, those will be evaluated into an escape sequence along with the character(s) following them. At this point it's too late to replace the backslashes as they are removed from the resulting string.

It's a string literal.. By the time it's assigned to imagepath, the escape sequences are already parsed and processed, and the backslashes no longer exist in the string. You just have to have them in the string in the first place.
To demonstrate what I mean:
>>> var imagepath="C:\Documents and Settings\Mahesh\Desktop\images\advts.png"
>>> imagepath
"C:Documents and SettingsMaheshDesktopimagesadvts.png"
There's no way to fix the issue at that stage.

You can use the string replace() method. Replace on W3Schools.com.
Example:
var imagepath="C:\Documents and Settings\Mahesh\Desktop\images\advts.png"
document.write(imagepath.replace("\\", "\\\\"));
Upate As reko_t said, once a path is assigned to imagepath, it's a processed literal. The \ characters disappears. I've just tested my code with this example and there's no way to fix it unfortunately.
<html>
<head>
<script type="text/javascript">
function init() {
var imagepath="C:\Documents and Settings\Mahesh\Desktop\images\advts.png"
alert(imagepath.replace(/\\/g, "\\\\"));
}
</script>
</head>
<body onload="init()">
</body>
</html>
The only way to do it, is to replace \ to \\ on server side, and assign it to imagepath before it gets rendered to javascript that needs to be used by javascript.

Just add after var imagepath initialisation
var imagepath=imagepath.replace("\", "\\");
return imagepath;

Try this :
str.replace(new RegExp('/', 'g'),'-')

Related

How to fix 'missing) after argument list' error in Javascript

Why is this giving me this error?
<script>
function loadImg() {
var imageChosen = document.getElementById('imageChosen').value.replace("C:\fakepath\","");
alert(imageChosen);
document.getElementById('image').src = imageChosen;
}
</script>
I expect the image with id "image" to show the chosen image.
The value in your call to replace() is not escaped properly.
The value should instead be:
"C:\\fakepath\\",""
Read more about escaping strings here
The problem is due to the escape string character \ (backslash)
When using strings in Javascript we may escape some character in the string. For example a break line (\n) or even a "(double quotes) when declaring the string or even an backslash \ need a escape.
Examples:
x = "my \\" // Will output as the same as "my \"
z = "my \"quotes\" // Will output as 'my "quotes" '

Split string str.split("\\") using javascript

i have a string "demo1\demo2".
var str="demo1\demo2";
console.log(str.split("\\")[1])); \\gives undefined
console.log(str.split("\")[1])); \\gives undefined
gives undefined.
i need to demo2 in console.log
You're escaping the d after the \ in str. You need to escape the \ in str:
const str = 'demo1\\demo2';
console.log(str.split('\\'));
Just like #SimpleJ already answered, you need to escape your backslash so that it is not considered to be escaping the next character itself. As proof, when you don't escape your backslash with another backslash, here is how your string gets outputted (in case you haven't checked this yourself already):
> console.log('demo1\demo2')
demo1
undefined
> console.log('demo1\\demo2')
demo1\demo2
undefined
> console.log("demo1\demo2")
demo1
undefined
> console.log("demo1\\demo2") // same goes for double quoted strings
demo1\demo2
undefined
So this is the way to go:
"demo1\\demo2".split("\\")
If the items inside need escaping, you could run it through something like this first.
If you just need 'demo2' and you know what characters it has, you could something like:
console.log(str.match(/[^a-z0-9A-Z]([a-z0-9A-Z]*)$/)[1]);
or similar.

Regex to match forward or backward slash

I have a string like this :
whatever/aaazzzzz
and sometimes a string like that :
whatever\bbbbzzzzz
I would like to split the string when I match / or \
The regex I tried seems to work
https://regex101.com/r/gP5gL0/1
When I use it in the fiddle, it works with / but not with \
Any ideas?
The issue here is not the regex itself, but the unavoidable fact that JavaScript doesn't implicitly support string literals (i.e. ones where backslashes are interpreted as printed as opposed to denoting an escape sequence. Much more can read here).
Strings derived from any source other than source code are interpreted as literal by default, as demonstrated in this fiddle.
<script>
function splitTheString()
{
//test = escape("whatever\aaaaaa");
var test = document.getElementById("strToSplit").value;
a = test.split(/(\\|\/)/)[0];
alert(a);
}
</script>
<form>
Split this string:<br>
<input type="text" id="strToSplit">
Split the string
</form>
Use this
var arr = str.split(/[\\|\/]/);
var str = 'whatever\\bbbbzzzzz';
alert(str.split(/[\\|\/]/))

Replace all \" with \\" in javascript

I want to replace all \" in my string with \\" (\" in <div style=\"font-size:0.9em\">)
var str = '{"CarID":"Z100","alerts":[{"AlertType":"Head <b>southeast</b> on <b>Tân Hải</b> toward <b>Trường Chinh</b><div style=\"font-size:0.9em\">Pass by nhan cuoi dep (on the right)</div>"}],"customizedLocations":[]}';
str = str.replace(/\"/g, '\\\\"');
I want the output is (\" in style is replaced by \\"):
{"VehicleID":"Z100","alerts":[{"AlertType":"Head <b>southeast</b> on <b>Tân Hải</b> toward <b>Trường Chinh</b><div style=\\"font-size:0.9em\\">Pass by nhan cuoi dep (on the right)</div>"}],"customizedLocations":[]}
But actually I get is (ALL " is replaced by \\"):
{\\"VehicleID\\":\\"Z100\\",\\"alerts\\":[{\\"AlertType\\":\\"Head <b>southeast</b> on <b>Tân Hải</b> toward <b>Trường Chinh</b><div style=\\"font-size:0.9em\\">Pass by nhan cuoi dep (on the right)</div>\\"}]}
I don't want to use jQuery, can somebody help me!
There is a little problem in your regex. The backslash \ means escape. So when you write \" it finds only one quotation mark, the backslash escapes it as it is a special character.
You have to escape both the backslash and the quotation mark:
str = str.replace(/\\\"/g, '\\\\"');
This will produce the wished result.
Please read the comment from the user zerkms below your question. I don't really understand what this replacing is good for. Maybe you have the so called x-y problem:
https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem
EDIT:
The above posted code line want work, because of the reasons explained in the comment below from the user zerkms. There is a workaround using raw string:
String.raw`\"`.replace(/\"/g, '\\"');
This is tested and should work.
If you are fetching a path from HTML input tag and you need to replace the \ in path with \\ for further processing in code. You can use the following
var myString = $('#myID').val(); // c:\User\path
console.log(myString.split('\\').join('\\\\')); // c:\\User\\path

Why this JavaScript RegExp results in dual answer?

Look at this simple HTML input tag:
<input type='text' id='phoneNumber' name='phoneNumber' class='inputBig textLeft'
data-validation='required regex'
data-validation-regex-pattern='^\\+\\d{2}\\.\\d{10}$'
value='+98.2188665544' />
<p id='log'></p>
Now imagine that we want to validate this field, using this function:
var log = $('#log');
function validateRegex(field) {
var pattern = field.attr('data-validation-regex-pattern');
log.append(pattern + '<br />');
if (pattern && pattern != '') {
var isValid = new RegExp(pattern).test(field.val().trim());
if (!isValid) {
log.append('not valid<br />');
}
else {
log.text('valid<br />');
}
}
}
validateRegex($('#phoneNumber'));
var isValid = new RegExp('^\\+\\d{2}\\.\\d{10}$').test($('#phoneNumber').val());
log.append(isValid.toString());
Now, if you look at the log, you see that this line returns false:
var isValid = new RegExp(pattern).test(field.val().trim());
However, this line of code returns true:
new RegExp('^\\+\\d{2}\\.\\d{10}$').test($('#phoneNumber').val().trim());
In other words, when the pattern of the RegExp object is passed to it as a string variable, it doesn't work. But when you pass a string literal, it works.
Why? What's wrong here?
To see it in action, look at this fiddle.
Escaping backslashes applies only to JavaScript, it isn't necessary for HTML. Therefore, the following attribute string:
data-validation-regex-pattern='^\+\d{2}\.\d{10}$'
Will work just fine:
Updated fiddle: http://jsfiddle.net/AndyE/GRL2m/6/
\\ is the method to write \ in a JavaScript String. The HTML data-attribute, written in JS would be \\\\, instead of \\.
Eg: <a data-x="\\">(HTML) is equivalent to '<a data-x="\\\\">' (JS).
To get your code work, replace double slashes (\\) in your HTML by a single slash.Fiddle: http://jsfiddle.net/GRL2m/5/
Extra information:
In HTML, HTML entities (eg ") are used to display special characters.
In JavaScript, escapes (eg \n, \x20, \u0009, ..) are used to display special characters.
In a RegExp, special RE characters have to be escaped by a slash (/\./). When the RegExp is constructed using a string, the slash has to be escaped, so that the slash also appear at the RegExp. "\." equals '.', while "\\." equals '\.'.

Categories

Resources