Only one backslash in javascript - javascript

I know that backslash is escape character in js. And to display one backslash, I need to write two.
But I am having express server that send request to database and here I need to add only one backslash. SO if filter contains two backslashes, replace it only with one. How to write it?
filter.replace("\\", String.fromCharCode(92)); //do two not one
filter.replace("\\", "\"); //doesn't work, syntax error
"aaaa\\aaaa" - > "aaaa\aaaa"
Another ideas?
The string that is send to database contains two backslashes but js GUI shows only one (of course).

How to write it?
You said it yourself:
to display one backslash, I need to write two.
So, if you have two in the string to start with, then you need to replace two (type four) with one (type two).
var filter = "This string has a double slash in it: \\\\";
console.log(`The original string: ${filter}`);
filter = filter.replace("\\\\", "\\");
console.log(`The filtered string: ${filter}`);

Quentin answered your question, but another way to think about it is that two backslashes written into a sting will resolve to a single backslash as soon as you do anything with it.
For example:
//Returns Error
//Returns: \
var i = "this is a backslash \\"
//i now contains only one backslash
//Returns: this is a backslash \
Since you clarified that it's after this in the querying that it gets messed up, you could try making sure you've assigned it to a variable and then passed it to the query.
i = "A string containing backslashes \\"
Edit 2:
Oh, I just got it, you're trying to escape colons ':' which is already handled in JS. So if the query isn't parsing your escape characters than just \: should be perfectly valid.


How to make replace() global in JavaScript

I know this question had been asked lot of time but i could not find solution. I have some smilies which each of them has code to be rendered as smiley using replace() , but I get syntax error, I don't know why and how to render my code :/ to smiley
txt = " Hi :/ ";
txt.replace("/\:/\/g","<img src='img/smiley.gif'>");
There are two problems in the first argument of replace() it escapes the wrong characters and it uses a string that seems to contain a regex instead of a real RegExp.
The second line should read:
txt.replace(/:\//g,"<img src='img/smiley.gif'>");
/:\//g is the regex. The first and the last / are the RegExp delimiters, g is the "global" RegExp option (String.replace() needs a RegExp instead of a string to do a global replace).
The content of the regex is :/ (the string you want to find) but because / has a special meaning in a RegExp (see above), it needs to be escaped and it becomes :\/.
Your regular expression doesn't need to be in quotes. You should escape the correct / forward slash (you were escaping the wrong slash) and assign the replacement, since .replace doesn't modify the original string.
txt = " Hi :/ ";
txt = txt.replace(/:\//g,"<img src='img/smiley.gif'>");
Based on jonatjano's brilliant deduction, I think you should add a little more to the regular expression to avoid such calamities as interfering with URLs.
txt = txt.replace(/:\/(?!/)/g,"<img src='img/smiley.gif'>");
The above ensures that :// is not matched by doing a negative-lookahead.

How to split a string in javascript by special char \

I believe that this is simple and I'm missing something. I want to split a physical path in windows with javascript. So I try with String#split function, but my result was inespected.
For this string
I'm getting this result
var test = "C:\CLC\VIDA\Web\_REPOSITORIO\Colectivos\ReembolsosWeb\TMP_011906169_01_01.pdf";
test.split("\"); //throws error
test.split("\\"); //result in -> ["C:CLCVIDAWeb_REPOSITORIOColectivosReembolsosWebTMP_011906169_01_01.pdf"]
test.split(/\\/); // -> the regex is the same as above
One last thing, in my test, I found that to get the result that I want I could do it like this
var test2 = "C:\\CLC\\VIDA\\Web\\_REPOSITORIO\\Colectivos\\ReembolsosWeb\\TMP_011906169_01_01.pdf"
test2.split("\\"); // -> ["C:", "CLC", "VIDA", "Web", "_REPOSITORIO", "Colectivos", "ReembolsosWeb", "TMP_011906169_01_01.pdf"]
So my question is, how can I split the string from test var to get the array from the last case?
Strings in javascript support escape sequences via the backslash (\). For example if you need a tab in your string you can add a \t anywhere in your string and it will be replaced with a tab, a \n will be replaced with a new line.
The backslashes in test are either converted to their respective characters or dropped because they are invalid escape sequences.
To get around this you can escape one backslash with another to get a single normal backslash. The downside is that this cannot be done in javascript. Generally I paste my string in to notepad/N++/Code/Sublime and replace all \ with \\
Since you are hard coding the string you need to escape all backslashes. After that you can use test.split("\\") which, itself contains an escaped backslash.
So, as far as Javascript is concerned, your code looks like this.
var test = "C:CLCVIDAWeb_REPOSITORIOColectivosReembolsosWebTMP_011906169_01_01.pdf";
To make javascript see the string correctly you need to make it look like this...
var test = "C:\\CLC\\VIDA\\Web\\_REPOSITORIO\\Colectivos\\ReembolsosWeb\\TMP_011906169_01_01.pdf";
Firstly, note that when you have a single backslash in a string, it is used for escaping the next character. It is just ignored if there is no special character next to it to escape.
Now, just have a look at your string :
var test = "C:\CLC\VIDA\Web\_REPOSITORIO\Colectivos\ReembolsosWeb\TMP_011906169_01_01.pdf"
Don't you think all of your single backslashes will be ignored here?
So, the solution is simple, what you have already tried successfully. To escape all your backslashes with another backslash.
var test2 = "C:\\CLC\\VIDA\\Web\\_REPOSITORIO\\Colectivos\\ReembolsosWeb\\TMP_011906169_01_01.pdf"
test2.split("\\"); // -> ["C:", "CLC", "VIDA", "Web", "_REPOSITORIO", "Colectivos", "ReembolsosWeb", "TMP_011906169_01_01.pdf"]
But, are you worried about any dynamic data which has such backslash? (For example, coming from a text input or a file input.) Don't think about escaping the backslash inside it. Because you don't need to do that! It's already a well formatted string for you, which you can use as it is. You need to escape only when you are hard coding the string yourself.

Regex: get string between last character occurence before a comma

I need some help with Regex.
I have this string: \\lorem\ipsum\dolor,\\sit\amet\conseteteur,\\sadipscing\elitr\sed\diam
and want to get the result: ["dolor", "conseteteur", "diam"]So in words the word between the last backslash and a comma or the end.
I've already figured out a working test, but because of reasons it won't work in neitherChrome (v44.0.2403.130) nor IE (v11.0.9600.17905) console.There i'm getting the result: ["\loremipsumdolor,", "\sitametconseteteur,", "\sadipscingelitrseddiam"]
Can you please tell me, why the online testers aren't working and how i can achieve the right result?
Thanks in advance.
PS: I've tested a few online regex testers with all the same result. (,,,
The string
is getting escaped, if you try the following in the browser's console you'll see what happens:
var s = '\\lorem\ipsum\dolor,\\sit\amet\conseteteur,\\sadipscing\elitr\sed\diam'
// prints '\loremipsumdolor,\sitametconseteteur,\sadipscingelitrseddiam'
To use your original string you have to add additional backslashes, otherwise it becomes a different one because it tries to escape anything followed by a single backslash.
The reason why it works in regexp testers is because they probably sanitize the input string to make sure it gets evaluated as-is.
Try this (added an extra \ for each of them):
str = '\\\\lorem\\ipsum\\dolor,\\\\sit\\amet\\conseteteur,\\\\sadipscing\\elitr\\sed\\diam'
re = /\\([^\\]*)(?:,|$)/g
// should output ["\dolor,", "\conseteteur,", "\diam"]
You can't prevent the interpreter from escaping backslashes in string literals, but this functionality is coming with EcmaScript6 as String.raw
s = String.raw`\\lorem\ipsum\dolor,\\sit\amet\conseteteur,\\sadipscing\elitr\sed\diam`
Remember to use backticks instead of single quotes with String.raw.
It's working in latest Chrome, but I can't say for all other browsers, if they're moderately old, it probably isn't implemented.
Also, if you want to avoid matching the last backslash you need to:
remove the \\ at the start of your regexp
use + instead of * to avoid matching the line end (it will create an extra capture)
use a positive lookahead ?=
like this
s = String.raw`\\lorem\ipsum\dolor,\\sit\amet\conseteteur,\\sadipscing\elitr\sed\diam`;
re = /([^\\]+)(?=,|$)/g;
// ["dolor", "conseteteur", "diam"]
You may try this,

RegExp for remove first and last char and turn ending double slashes into single

I have the following Javascript code to obtain the inner string from an RegExp:
Function.prototype.method = function (name,func){
this.prototype[name] = func;
return this;
RegExp.method('toRawString', function(){
return this.toString().replace(/^.(.*).$/,"$1");
The purpose of this, is to avoid in string double quoting. For example, if you have a Windows file path "C:\My Documents\My Folder\MyFile.file", you can use it like the following:
alert(/C:\My Documents\My Folder\MyFile.file/.toRawString());
However it is not working for ""C:\My Documents\My Folder\" since it causes syntax error. The only way to avoid it is to keep double quoting at the end of the string. Thus it will be written
alert(/C:\My Documents\My Folder\\/.toRawString());
The fact is any odd number of back slashes on the end of the string will be an error, so all ending back slashes must be double escaped. It will not be hard to use a multiple line small implementation, but are there any single RegExp solution?
When using toRawString the RegExp object for this is usually NOT going to be used for any other purpose except for that method. I just want to use the syntax of RegExp to avoid double back slashes in source code. Unfortunately the ending double slashes cannot be easily avoid. I think another workaround is to force a space at the end but that is another question then.
I finally solved the "another question" and posted the code here.
OK, I get what you're trying to do! It's hacky : )
Try something like:
return this.toString().slice(1, -1).replace(/\\+$/, '\\')
Hope that helps.
If you want to include the double quotes in the string just wrap it with single quotes.
s = '"C:\\My Documents\\My Folder\\MyFile.file"'
console.log(s) // Output => "C:\My Documents\My Folder\MyFile.file"
This produces a syntax error:
/C:\My Documents\/
But that regular expression could be written correctly like this:
/C:\\My Documents\\/
Or like this:
new RegExp("C:\\\\My Documents\\\\")
I think your function is just fine and is returning a correct result. Regular expressions just can't end with an unpaired backslash. It's not that you're double escaping - you're just escaping the escape character.
This would produce an error too:
new RegExp("C:\\My Documents\\")
A regular expression like this, for instance, can't be written without a pair of backslashes:
Without the second backslash, \W would be interpreted as a special character escape sequence. So escaping the escape character isn't only necessary at the end. It's required anywhere it might be interpreted as the beginning of an escape sequences. For that reason, it might be a good rule of thumb to always use two backslashes to indicate a backslash literal in a regular expression.

How do I replace a double-quote with an escape-char double-quote in a string using javascript?

Say I have a string variable (var str) as follows-
Dude, he totally said that "You Rock!"
Now If I'm to make it look like as follows-
Dude, he totally said that \"You Rock!\"
How do I accomplish this using the JavaScript replace() function?
str.replace("\"","\\""); is not working so well. It gives unterminated string literal error.
Now, if the above sentence were to be stored in a SQL database, say in MySQL as a LONGTEXT (or any other VARCHAR-ish) datatype, what else string optimizations I need to perform? Quotes and Commas are not very friendly with query strings. I'd appreciate a few suggestions on that matter as well.
You need to use a global regular expression for this, try it this way
str.replace(/"/g, '\\"');
check out regex syntax and options for the replace function here:
Try this:
str.replace("\"","\\\""); // (escape backslashes and embedded double-quotes)
Or, use single-quotes to quote your search and replace strings:
str.replace('"','\\"'); // (still need to escape the backslash)
UPDATE: As pointed out by helmus, if the first parameter passed to .replace() is a string it will only replace the first occurrence. To replace globally you have to pass a regex with the g (global) flag:
// or
But why are you even doing this in JavaScript? It's OK to use these escape characters if you have a string literal like:
var str = "Dude, he totally said that \"You Rock!\"";
But this is necessary only in a string literal. That is, if your JS variable is set to a value that a user typed in a form field you don't need to this escaping.
Regarding your question about storing such a string in an SQL database, again you only need to escape the characters if you're embedding a string literal in your SQL statement - and remember that the escape characters that apply in SQL aren't (usually) the same as for JS. You'd do any SQL-related escaping server-side.
The other answers will work for most strings, but you can end up unescaping an already escaped double quote, which is probably not what you want.
To work correctly, you are going to need to escape all backslashes and then escape all double quotes, like this:
var test_str = '"first \\" middle \\" last "';
var result = test_str.replace(/\\/g, '\\\\').replace(/\"/g, '\\"');
depending on how you need to use the string, and the other escaped charaters involved, this may still have some issues, but I think it will probably work in most cases.
var str = 'Dude, he totally said that "You Rock!"';
var var1 = str.replace(/\"/g,"\\\"");