Escaping backslash in string - javascript - javascript

I need to show the name of the currently selected file (in <input type="file"> element).
Everything is fine, the only problem is I'm getting this kind of string "C:\fakepath
\typog_rules.pdf" (browset automatically puts this as value for the input element).
When I try to split the string by '\' or '\\' it fails because of unescaped slashes. Attempts to match/replace slashes fails too. Is there a way around this? I need this to work at least in Opera and IE (because in other browsers I can use FileReader)
E.G. I'm getting "C:\fakepath\typog_rules.pdf" as input and want to get "typog_rules.pdf" as output.

For security reasons, it is not possible to get the real, full path of a file, referred through an <input type="file" /> element.
This question already mentions, and links to other Stack Overflow questions regarding this topic.
Previous answer, kept as a reference for future visitors who reach this page through the title, tags and question.
The backslash has to be escaped.
string = string.split("\\");
In JavaScript, the backslash is used to escape special characters, such as newlines (\n). If you want to use a literal backslash, a double backslash has to be used.
So, if you want to match two backslashes, four backslashes has to be used. For example,alert("\\\\") will show a dialog containing two backslashes.

Escape the backslash character.
foo.split('\\')

I think this is closer to the answer you're looking for:
<input type="file">
$file = $(file);
var filename = fileElement[0].files[0].name;

Slightly hacky, but it works:
const input = '\text';
const output = JSON.stringify(input).replace(/((^")|("$))/g, "").trim();
console.log({ input, output });
// { input: '\text', output: '\\text' }

Add an input id to the element and do something like that:
document.getElementById('inputId').value.split(/[\\$]/).pop()

Related

Regex javascript to only return a value and not full match

How do we do look behind in java script like we can in java or php?
RegEx works for php parser using lookbehind
Here is the working Regex using php parser.
(?<=MakeName=)(.*?)([^\s]+)
This produces the value
(MakeName=)(.*?)([^\s]+)
this produces the match + value
xml response to extract value from.
<ModelName="Tacoma" MakeName="Tundra" Year="2015">
I just need the value
There is no look-behind in JavaScript.
If you are sure the attribute MakeName is present in the input, then you could use this regular expression:
/[^"]*(?!.*\sMakeName\s*=)(?="([^"]*"[^"]*")*[^"]*$)/
It grabs the first series of characters that do not contain a double quote and have a double quote immediately following it, with an even number of double quotes following after that until the end of the input (to make sure we are matching inside a quoted string), but MakeName= should not occur anywhere after the match.
This is of course still not bullet proof, as it will fail for some boundary cases, like with single quoted values.:
<ModelName="Tacoma" MakeName='Tundra' Year="2015">
You could resolve that, if needed, by repeating the same pattern, but then based on single quotes, and combining the two with an OR (|).
Demo:
var s = '<ModelName="Tacoma" MakeName="Tundra" Year="2015">';
result = s.match(/[^"]*(?!.*\sMakeName\s*=)(?="([^"]*"[^"]*")*[^"]*$)/);
console.log(result[0]);

carriage return encoding

through queries to a Database I am retrieving such data that I previously inserted through HTML textarea or input. When I get the response from my DB , in a JSON object the text field looks like this :
obj : {
text : [some_text] ↵ [some_text]
}
I tried to replace with this function :
string_convert = function(string){
return string.replace("&#8629",'<br>')
.replace('&crarr','<br>')
.replace('/[\n\r]/g','<br>');
}
I have to show this string in HTML ,but it does not seems to work. I'm using UTF-8
Any advice?
The problem you have is that you have enclosed your regex in quotes. This is incorrect.
.replace('/[\n\r]/g','<br>');
^ ^
remove these two quotes
The quotes are unnecessary because the regex is already delimited by the slashes.
By putting quotes in there, you've actually told it that you want to replace a fixed string rather than a regular expression. The fixed string may look like an expression, but with the quotes, it will just be seen as a plain string.
Remove the quotes and it will be seen as an expression, and it will work just fine.
One other thing, though -- in order to make your regex work perfectly, I'd also suggest modifying it slightly. As it stands, it will just replace all the \n and \r characters with <br>. But in some cases, they may come together as a \r\n pair. This should be a single line break, but your expression will replace it with two <br>s.
You could use an expression like this instead:
/\r\n|\n|\r/g
Hope that helps.
you are missing the ending semicolons ; in your code:
string_convert = function(aString){
return aString.replace("↵",'<br>').replace('↵','<br>');
}
this does not necessary solve your problem, but it could likely.
From: Trying to translate a carriage return into a html tag in Javascript?
text = text.replace(/(\r\n|\n|\r)/g,"<br />");

Escape single quote with JavaScript

I am aware with escaping special characters in HTML.
But, I am still asking this as I have come across a situation.
I have a JSP, in which I am not allowed put validation on input. Users are entering special characters to test.
Input string:
'##$%
When I am displaying from database, I am using
<%= StringEscapeUtils.escapeHtml(map[i].get("text").toString())%>
where "map" is an array of Hashmap. This works fine.
The problem comes when I need to pass this string to JavaScript using
<input type="Button"
onclick="onEdit('<%= StringEscapeUtils.escapeHtml(map[i].get("text").toString())%>',
'<%= strShortCut%>','<%= map[i].get("uid")%>')" value="Edit">
The string becomes ''##$%'.
How do I escape a single quote?
If you would be using Java, maybe you can do the below in Java.
import org.apache.commons.lang.StringEscapeUtils;
...
String result = StringEscapeUtils.escapeJavaScript(jsString);
Just prepend every single quote with a backslash. Like the following:
StringEscapeUtils.escapeHtml(map[i].get("text").toString()).replace("\'","\\'")
But your problem is not only in the single quote. There is also the double quote (") and the backslash itself (\).
Use the same technique as shown before. You can also use regular expressions, but I showed you the simplest way.
To check the escape characters, look at the URL http://docs.oracle.com/javase/tutorial/java/data/characters.html.

escape hidden character that is causing JSON validation to fail

I have a hidden character that is causing JSON parsing to fail. What is the best way to escape a string properly just that hidden characters like these done crash my json?
Here is the code, the invisible character is between the n and the s in "brains" until you remove that invisible character JSON.parse() will fail... question is, how to strip the invisible character?
var mystring='{"invis":"their brains process differently"}';
console.log("cool" + mystring);
console.log(JSON.parse(mystring));
Note I found that in the above code actually removed the invisible character, but it is here on pastie, if you want to copy and paste to see the issue:
See the code on pastie
Somehow a cancel character (0x18) got into your string. You can simply replace it out with a regular expression.
var mystring='{"invis":"their brains process differently"}';
mystring = mystring.replace( /\x18/g, "" );
console.log("cool" + mystring);
console.log(JSON.parse(mystring));
I found another JSON parser that doesnt crash with these hidden characters, it is located here:
https://github.com/douglascrockford/JSON-js

JavaScript backslash (\) in variables is causing an error

In Javascript, when I put a backslash in some variables like:
var ttt = "aa ///\\\";
var ttt = "aa ///\";
Javascript shows an error.
If I try to restrict user in entering this character, I also get an error:
(("aaa ///\\\").indexOf('"') != -1)
Restricting backslashes from user input is not a good strategy, because you have to show an annoying message to the user.
Why am I getting an error with backslash?
The backslash (\) is an escape character in Javascript (along with a lot of other C-like languages). This means that when Javascript encounters a backslash, it tries to escape the following character. For instance, \n is a newline character (rather than a backslash followed by the letter n).
In order to output a literal backslash, you need to escape it. That means \\ will output a single backslash (and \\\\ will output two, and so on). The reason "aa ///\" doesn't work is because the backslash escapes the " (which will print a literal quote), and thus your string is not properly terminated. Similarly, "aa ///\\\" won't work, because the last backslash again escapes the quote.
Just remember, for each backslash you want to output, you need to give Javascript two.
You may want to try the following, which is more or less the standard way to escape user input:
function stringEscape(s) {
return s ? s.replace(/\\/g,'\\\\').replace(/\n/g,'\\n').replace(/\t/g,'\\t').replace(/\v/g,'\\v').replace(/'/g,"\\'").replace(/"/g,'\\"').replace(/[\x00-\x1F\x80-\x9F]/g,hex) : s;
function hex(c) { var v = '0'+c.charCodeAt(0).toString(16); return '\\x'+v.substr(v.length-2); }
}
This replaces all backslashes with an escaped backslash, and then proceeds to escape other non-printable characters to their escaped form. It also escapes single and double quotes, so you can use the output as a string constructor even in eval (which is a bad idea by itself, considering that you are using user input). But in any case, it should do the job you want.
You have to escape each \ to be \\:
var ttt = "aa ///\\\\\\";
Updated: I think this question is not about the escape character in string at all. The asker doesn't seem to explain the problem correctly.
because you had to show a message to user that user can't give a name which has (\) character.
I think the scenario is like:
var user_input_name = document.getElementById('the_name').value;
Then the asker wants to check if user_input_name contains any [\]. If so, then alert the user.
If user enters [aa ///\] in HTML input box, then if you alert(user_input_name), you will see [aaa ///\]. You don't need to escape, i.e. replace [\] to be [\\] in JavaScript code. When you do escaping, that is because you are trying to make of a string which contain special characters in JavaScript source code. If you don't do it, it won't be parsed correct. Since you already get a string, you don't need to pass it into an escaping function. If you do so, I am guessing you are generating another JavaScript code from a JavaScript code, but it's not the case here.
I am guessing asker wants to simulate the input, so we can understand the problem. Unfortunately, asker doesn't understand JavaScript well. Therefore, a syntax error code being supplied to us:
var ttt = "aa ///\";
Hence, we assume the asker having problem with escaping.
If you want to simulate, you code must be valid at first place.
var ttt = "aa ///\\"; // <- This is correct
// var ttt = "aa ///\"; // <- This is not.
alert(ttt); // You will see [aa ///\] in dialog, which is what you expect, right?
Now, you only need to do is
var user_input_name = document.getElementById('the_name').value;
if (user_input_name.indexOf("\\") >= 0) { // There is a [\] in the string
alert("\\ is not allowed to be used!"); // User reads [\ is not allowed to be used]
do_something_else();
}
Edit: I used [] to quote text to be shown, so it would be less confused than using "".
The backslash \ is reserved for use as an escape character in Javascript.
To use a backslash literally you need to use two backslashes
\\
If you want to use special character in javascript variable value, Escape Character (\) is required.
Backslash in your example is special character, too.
So you should do something like this,
var ttt = "aa ///\\\\\\"; // --> ///\\\
or
var ttt = "aa ///\\"; // --> ///\
But Escape Character not require for user input.
When you press / in prompt box or input field then submit, that means single /.

Categories