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
example
"aaaa\\aaaa" - > "aaaa\aaaa"
Another ideas?
---UPADTE---
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:
Console.Log("\");
//Returns Error
Console.Log("\\");
//Returns: \
var i = "this is a backslash \\"
//i now contains only one backslash
Console.Log(i);
//Returns: this is a backslash \
Edit:
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 \\"
sql.Query(i);
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.

Related

Why do I need to replace \n with \n?

I have a line of data like this:
1•#00DDDD•deeppink•1•100•true•25•100•Random\nTopics•1,2,3,0•false
in a text file.
Specifically, for my "problem", I am using Random\nTopics as a piece of text data, and I then search for '\n', and split the message up into two lines based on the placement of '\n'.
It is stored in blockObj.msg, and I search for it using blockObj.msg.split('\n'), but I kept getting an array of 1 (no splits). I thought I was doing something fundamentally wrong and spent over an hour troubleshooting, until on a whim, I tried
blockObj.msg = blockObj.msg.replace(/\\n/g, "\n")
and that seemed to solve the problem. Any ideas as to why this is needed? My solution works, but I am clueless as to why, and would like to understand better so I don't need to spend so long searching for an answer as bizarre as this.
I have a similar error when reading "text" from an input text field. If I type a '\n' in the box, the split will not find it, but using a replace works (the replace seems pointless, but apparently isn't...)
obj.msg = document.getElementById('textTextField').value.replace(/\\n/g, "\n")
Sorry if this is jumbled, long time user of reading for solutions, first time posting a question. Thank you for your time and patience!
P.S. If possible... is there a way to do the opposite? Replace a real "\n" with a fake "\n"? (I would like to have my dynamically generated data file to have a "\n" instead of a new line)
It is stored in blockObj.msg, and I search for it using blockObj.msg.split('\n'),
In a JavaScript string literal, \n is an escape sequence representing a new line, so you are splitting the data on new lines.
The data you have doesn't have new lines in it though. It has slash characters followed by n characters. They are data, not escape sequences.
Your call to replace (blockObj.msg = blockObj.msg.replace(/\\n/g, "\n")) works around this by replacing the slashes and ns with new lines.
That's an overcomplicated approach though. You can match the characters you have directly. blockObj.msg.split('\\n')
in your text file
1•#00DDDD•deeppink•1•100•true•25•100•Random\nTopics•1,2,3,0•false
means that there are characters which are \ and n thats how they are stored, but to insert a new line character by replacement, you are then searching for the \ and the n character pair.
obj.msg = document.getElementById('textTextField').value.replace(/\\n/g, "\n")
when you do the replace(/\\n/g, "\n")
you are searching for \\n this is the escaped version of the string, meaing that the replace must find all strings that are \n but to search for that you need to escape it first into \\n
EDIT
/\\n/g is the regex string..... \n is the value... so /\REGEXSTUFFHERE/g the last / is followed by regex flags, so g in /g would be global search
regex resources
test regex online

JSON Parse Unexpected token h caused quotes inside string value

I have a JSON string that I got from the table, here's my JSON
{"subtitle":"Information","desc":"Hi, Welcome.\\n <br><br>\\n You can access our website here.\\n <br><br>\\n Dont forget, cost: only $2! \\n <br>\\n <br>\\n <br>\\n <br>\\n Thankyou,<br>\\n Regards"}
when I'm trying to do json.parse() but I got an error
SyntaxError: Unexpected token h in JSON at position 154.
I thought it caused because of the quotes " in URL or colon :.
How do I can pass them to JSON?
Update
Here's how I got the data:
var body_inbox = {};
body_inbox.subtitle = 'Information';
body_inbox.desc = `Hi, Welcome.
<br><br>
You can access our website here.
<br><br>
Dont forget, cost: only $2!
<br>
<br>
<br>
<br>
Thankyou,<br>
Regards`;
body_inbox = JSON.stringify(body_inbox);
I am confused, I found many data in table that data has double backslash in newline \\n and in url here. I just try create new data with JSON.stringify and the result is \n and here. Why does this happen?
Note
Sorry, there's a misleading the earlier data is typo.
It should be <a href=\\"https://test.com\\"> not <a href="\\https://test.com\\">
The double backslashes should be single backslashes. A single backslash escapes the following character, so what you’re doing with the double is escaping the second backslash. It chokes on the href because the quote that follows ends the string, after which the parser hits the ‘h’ in the url as a raw character.
{ message: "...our website here" }
// ^ parser thinks the string ends here
// and doesn't know what to make of
// https://...
My guess is that the data got escaped twice by two different processes (or the same process run twice).
Hypothetical example: The data gets created, and on the way into the database it gets escaped. So now all quotes are preceded by a backslash. Then an edit is made to the data and the record is updated in the database, and the escaping gets run again. But the input string already has backslashes in it from the first time, and because backslashes themselves are special and need to be escaped, when the string gets escaped (again) on its way back to the database you end up with double backslashes.
You can see this kind of thing by escaping a string twice in the console. (This isn't doing backslashes, but it's demonstrative of the problem):
const input = '"This string is quoted."';
const once = encodeURI(input);
// encodes the quotes as '%22'
// "%22This%20string%20is%20quoted.%22"
const twice = encodeURI(once);
// encodes the '%' in '%22' as '%25', and you end up with `%2522`
// "%2522This%2520string%2520is%2520quoted.%2522"
Double quotes in json (in value) only require one forward slash(\).
So your json should be
{"subtitle":"Information","desc":"Hi, Welcome.\\n <br><br>\\n You can access our website here.\\n <br><br>\\n Dont forget, cost: only $2! \\n <br>\\n <br>\\n <br>\\n <br>\\n Thankyou,<br>\\n Regards"}
Use the template string to save data.
const json = `{"subtitle":"Information","desc":"Hi, Welcome.\\n<br><br>\\nYou can access our website here.\\n<br><br>\\nDont forget, cost: only $2!\\n<br>\\n<br>\\n<br>\\n<br>\\n Thankyou,<br>\\n Regards"}`
console.log(JSON.parse(json))
(Posted an answer from the question author to move it to the answer space).
Thank you so much for all the answers. It's helped to figure out that the parse failed caused by double backslash that escape the second backslash not the double quotes ".
The data has double backslash because of this is data from cloned database, I thought it happen during conversion to SQL file.

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
"C:\CLC\VIDA\Web\_REPOSITORIO\Colectivos\ReembolsosWeb\TMP_011906169_01_01.pdf"
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. (regex101.com, regexpal.com, debuggex.com, scriptular.com)
The string
'\\lorem\ipsum\dolor,\\sit\amet\conseteteur,\\sadipscing\elitr\sed\diam'
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'
console.log(s);
// 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
str.match(re)
// should output ["\dolor,", "\conseteteur,", "\diam"]
UPDATE
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;
s.match(re);
// ["dolor", "conseteteur", "diam"]
You may try this,
string.match(/[^\\,]+(?=,|$)/gm);
DEMO

Using \ character in textarea

This might be an stupid question for many of you, but I'm hitting a wall with the stupidest thing.
I'm displaying code in a textarea field, but the code includes the character \, so it disappears in the code shown.
This is the exact line:
'return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")'+
And this is what is displayed:
return x.toString().replace(/B(?=(d{3})+(?!d))/g, ",")
I know the solution is easy, but I can't find it
That is because the \ character is an escape character within strings in JavaScript. If you want the character itself to show, you need to escape it with another one: \\
So your code would need to be:
'return x.toString().replace(/\\B(?=(\\d{3})+(?!\\d))/g, ",")'+
To display a literal \ you could just convert it to it's HTML entity values using a table like this
For backslash you would want to type \
If the code snippets you want to print are stored in a DB and fetched via PHP you could always run a htmlentities() on them before echo:ing them to your frontend to ensure characters like backslash are displayed properly.

Categories

Resources