Replace all \" with \\" in javascript - 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

Related

How to insert a <CR> (Carriage Return) in a Javascript String?

I need to insert a Carriage Return in a String. As far as I know the \r should do it but here is the problem:
I wrote this in the browser console: 1\r2 then I get: 12 in return. Now I copy/paste it on Notepad++ https://imgur.com/a/pUW8p
There is a CR and a LF there. How I can add just a CR?
Note that you can replace the LF(\n) in notepad, save the file and the LFs are gone.
In ES6 with string templates you just introduce the carriage return as written text.
Also you can use \n to mark carriage return in quoted strings.
const str = `l
e`;
console.log(str);
const str2 = 'l\ne';
console.log(str2);
Usually, carriage returns often go like this...
\n
and you can use more than one to go down multiple lines.
It's the equivalent of pressing the enter/return key after you type one line and you want to move to the next one.
For example,
var astring = "This is a \n test";
print(astring);
You would get:
This is a
test
Hope it answers your question,
Alexander B.

Regex find string and replace that line and following lines

I am trying to find a regex to achieve the following criteria which I need to use in javascript.
Input file
some string is here and above this line
:62M:C111111EUR1211498,00
:20:0000/11111000000
:25:1111111111
:28C:00001/00002
:60M:C170926EUR1211498,06
:61:1710050926C167,XXNCHKXXXXX 11111//111111/111111
Output has to be
some string is here and above this line
:61:1710050926C167,XXNCHKXXXXX 11111//111111/111111
Briefly, find :62M: and then replace (and delete) the lines starting with :62M: followed by lines starting with :20:, :25:, :28c: and :60M:.
Or, find :62M: and replace (and delete) until the line starting with :61:.
Each line has fixed length of 80 characters followed by newline (CR LF).
Is this really possible with regex?
I know how to find a string and replace the same line where the string is. But here multiple lines to be removed which is quite hard for me.
Please could someone help me out if it is possible with regex.
Here it is. First I'm finding text to delete using regex (note that I'm using [^]* to match all the lines insted of .*, as it also matches newlines). Then I'm replacing it with a newline.
var regex = /:62M:.*([^]*):61:.*/;
var text = `some string is here and above this line
:62M:C111111EUR1211498,00
:20:0000/11111000000
:25:1111111111
:28C:00001/00002
:60M:C170926EUR1211498,06
:61:1710050926C167,XXNCHKXXXXX 11111//111111/111111`;
var textToDelete = regex.exec(text)[1];
var result = text.replace(textToDelete, '\n');
console.log(result);

Regex to change quoting style

In the text that I get, I want to replace all the dialogue quotes with double quotes, while keeping the single quotes used in contractions like "aren’t". I want to use a String.replace() with a regular expression to do this..
E:g:
var text = "'I'm the cook,' he said, 'it's my job.'";
console.log(text.replace(/*regEx*/, "\""));
//should return → "I'm the cook," he said, "it's my job."
Now I know a regex that works for me, at least for the example text.
console.log(text.replace(/\B'/g, "\""));
However, I wonder if there is any other regex I can use to accomplish this. Just curious.
I noticed that the regular expression you provided doesn't replace single quotes in the beginning of the string. I came up with this one instead:
var str = "'Hello', - she said\n'Hi!' - he whispered\n";
console.log(str.replace(/\B'|'\B/g, "\""));

Regexp won't work inside quotes

I use this Regexp to match text inside square brackets
/\[link\](.*)\[\/link\]/g
The text that I match
[link]The text goes here[/link]
The Regexp work's great when I test it in regex101 but when I use it in my website it doesn't work.
This is how I use it in my Website.
case 'untitle':
var html = '<script>$(document).ready(function(){var topic = $(".post-body div").text();
topic = topic.split(/\[link\](.*)\[\/link\]/g); $(".article-title a").attr("href", topic[1]);
});<\/script>';
break;
$('body').append(html);
I figure out that the Regexp doesn't work because it is inside quotes so I need a method to escape it and make it work.
Your issue is the fact that \ is an escape sequesnce so it is escaping the [ caharacter. You would need to double up the \\ in the string....
BUT the design is bad, it makes no sense to append JavaScript.
Well you are trying to run code for certain cases. It makes no sense why you are appending strings of code to the page.
function linkify () {
var topic = $(".post-body div").text();
topic = topic.split(/\[link\](.*)\[\/link\]/g); $(".article-title a").attr("href", topic[1]);
}
and the switch
case 'untitle':
linkify();
break;
Its not very clear what your exact problem is; but you are probably caught by the greediness of the regex. Basically, its matching entire [link]The text goes here[/link] foo [link] bar [/link] instead of just the first one. So you need to use \[link\](.*?)\[\/link\] instead.

Match #(\w+) and replace in javascript

I'm trying to match #(\w+) in a div content and remove it.
Here's what i've tried : http://jsfiddle.net/mxgde6m7/1/ .
#(\w+) works , but it doesn't replace with space.
var content = document.getElementById('contentbox');
var find = '#(\w+)';
var reg = new RegExp(find, 'g');
var result = content.innerHTML.replace(reg, ' ');
alert(result);
<div id="contentbox">#d test
What i want: <div id="contentbox">test
</div>
Thanks in advance.
EDIT
Okay, one problem solved, another one came up.
My script http://jsfiddle.net/mxgde6m7/9/ works perfectly there, but when i try it on my website, only a half works. The last part where it should replace #(\w+) with space doesn't work at all. If i copy/paste the CONTENT of the function in console(chrome), it works , but if i paste the function and i call it, it doesn't work.
Please help ! I'm stuck.
Using a RegExp constructor, you need two backslashes \\ in place of each backslash \.
var find = '#(\\w+)';
hwnd is correct that you need to double escape \w in your regular expression.
var find = '#(\\w+)';
But, you could also make this code much cleaner by defining a regex literal like so -
var content = document.getElementById('contentbox');
var result = content.innerHTML.replace(/#(\w+)/g, ' ');
alert(result);
Doing it this way doesn't require double escaping, as it's not a string.

Categories

Resources