I'm receiving this string from an external source (with a single backslash):
"Spool10072098_\P_18005389.txt"
Javascript completely ignoring "\", but I still need to get the string completely as I need to get the substring after it, P_18005389.txt in this case.
So my question is, how to get the substring after \ ?
Try String.raw method:
var example = String.raw`Spool10072098_\P_18005389.txt`;
console.log(example.split('\\')[1])
In your code, you need to escape a backslash, like this:
/* The memory will read "Spool10072098_\P_18005389.txt": */
var x = 'Spool10072098_\\P_18005389.txt';
Then you can split the string using split.
const second_part = x.split('\\')[1];
As you told us, the string you get from some other source than your source code, has only one backslash. That's okay, then the string in the memory contains the one backslash as you wanted.
Backslash is used in source code to mark up various special characters. That's why, if you want it to appear in your string, you need to escape it using another backslash.
For example:
"\n" /* will return a string containing a newline */
"\t" /* will return a string containing a tabulator */
"\\" /* will return a string containing a single \ character */
Related
I'd like to use a user provided string as argument for a JavaScript function and hence need to escape all characters that could cause the script to break.
This is for a Swift to JavaScript bridge to be used with WKWebView.evaluateJavaScript() that processes raw JavaScript.
window.someObject.method( ... user provided string ... )
The string can contain anything, line breaks, double quotes, backticks, unicode escape sequenced, substitutions, etc.
Currently I use a template literal and escape:
\ with \\ (single backslash with double backslash)
${ with \${
` with backslash+backtick
I'm trying to get this to work with String.raw, but I cannot figure out how to escape substitutions.
Potential user input:
hello ${1+1}
I want that exact string as argument to my JavaScript function, no substitutions being processed.
Here is what I tried:
// User input is: hello ${1+1}
console.log(String.raw`hello ${1+1}`)
console.log(String.raw`hello \${1+1}`) // So close, but not quite
console.log('I want: hello ${1+1}')
What I want is this:
window.someObject.method( String.raw`hello ${1+1}` ) → hello ${1+1}
Is this possible at all?
You can use this:
/**
* Prepare multi-line string for inclusion in JavaScript.
*
* Note! New line characters are added because slash (\) at the end of template string would brake template syntax.
* Starting new line is added for code beauty ;-).
*
* #param {String} text Some string.
*/
prepareTemplateString(text) {
if (text.search(/[`$]/)>=0) {
text = text.replace(/([`$])/g, '\\$1');
return "String.raw`\n"+text+"\n`.replace(/\\\\([`$])/g, '\\$1')";
}
return "String.raw`\n"+text+"\n`";
}
But I'm not happy with that. It seems that String.raw is actually slower then standard template string. I thought there would be some optimizations for String.raw but it seems it's just another layer on top of template strings.
I have a problem with regex in javascript. for example i have recorver list of programming language to my csv file. what i want is i must replace all the programming that have newline inside the double quote, and also the double quote with a space the sample output below. the output must be Ruby on Rails and C++ without double quote and newline.
SAMPLE OUTPUT
PYTHON
PHP
"Ruby on
Rails"
"C+
+"
I TRIED THIS CODE
how will i include also the new line inside the double quote
str.replace(/['"]+/g, ' ');
The difficulty with this question is that you have to find a way to know if the newline sequence must be replaced with a space or an empty string.
When the newline sequence is between word-boundaries, this means that there are a word character [a-zA-Z0-9_] before and after it (like in on\nRails). In this case it seems logical to send a space.
In other cases like C+\n+ or any other string that starts or ends with a newline, you can return an empty string.
txt = txt.replace(/"([^"]*)"/g, function (m,g) {
return g.replace(/\b([\r\n]+)\b|[\r\n]+/g, function(n,h) {
return h ? ' ' : '';
});
});
Let me know if you find other (interesting) edge cases.
I'm trying to sanitize quotes from a text input. Right now my code is:
string = string.replace(/'/g, '\'');
string = string.replace(/"/g, '\"');
My out put has all double quotes replaced, but the single quotes remain. I am fairly confident in my regex, and haven't had a problem with the replace function before. Is there a chance that mySQLdb is messing this up? I am posting it and then getting almost immediately after. This seems like such a simple issue but it really has me stumped
Your replacements are null operations since the backslash is consumed by the string literal itself and is not present in the actual string value.
Instead escape the backslash to really get one in your string:
string = string.replace(/'/g, "\\'");
string = string.replace(/"/g, '\\"');
You can of course do this in one operation:
string = string.replace(/(['"])/g, "\\$1");
I have a JSON string hardcoded in my Javascript.
valiJsonString = '{"ssss","ddddddddd\"ddd"}';
The DOM says -> {"ssss","ddddddddd"ddd"}
Can someone tell me why javascript replace my \" into " ?
// try to parse
valiJsonString secureEvalJSON (valiJsonString) //<-- error: jsonString is not valid
working example
"The DOM says" doesn't make much sense, as the DOM doesn't say anything. Do you mean the object browser in Firebug (or some other development console)?
Now, inside a string, \" is the quote character. You have to compensate for this escaping since you do not want it, but instead a verbatim slash.
So perhaps you want \\ followed by ", which is the slashed character followed by the quote character.
In addition, the given JSON looks like it ought to represent an array not an object, since you have no keys:
var str = '["ssss","ddddddddd\\"ddd"]';
The actual value of this JSON-format string inside your browser is now:
["ssss","ddddddddd\"ddd"]
\ is an escape character. try \\
If you want your string to come through escaped, then you need to escape your escape character:
valiJsonString = '{"ssss","ddddddddd\\"ddd"}';
I've added second \ (\ is escape char) and fixed lack of = and type of table {} vs []
http://jsfiddle.net/4wVaR/9/
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 /.