Javascript regex problems around \n - javascript

I have a text pattern that I am trying to replace in a node.js application. The pattern is:
***
some text
***
It is created in javascript with the following code:
var textblock = "***" + '\n' + 'some text' + '\n' + "***" + 'the rest of the text block'
The following regular expression works in regexpal and seems correct to me:
\*{3}\n.+\n\*{3}
But when I put it in my javascript code, it fails:
textblock.match(/\*{3}\n.+\n\*{3}/) // returns null
I tested, and even just *{3}\n doesn't seem to work. Am I missing something idiosyncratic about how javascript handles \n ? I've tried /m as well, and I've also tried [\n\r].
Thanks!
UPDATE: turns out that the GitHub API markdown processes issue body text and eliminates newlines. So my regex was correct, but I was wrong about the text I was matching in.

Try changing textblock to t:
var t = "***" + '\n' + 'some text' + '\n' + "***";
alert(t.match(/\*{1}\n.+\n\*{1}/));
(fiddle; removed some * from the regexp to check if it is working properly).

It might be an issue with line-endings. If you match for [\n\r] instead of just \n it works OK.
Here is a fiddle to demonstrate: http://jsfiddle.net/xD8a5/

The text I'm finding and replacing comes from a GitHub issue fetched via API. Turns out that when you put multiple asterisks in a row, they omit the newline chars before and after since they convert it into a graphical line.
The answer was to not require actual newline characters. This worked:
match(/\*{3}[\n\r]*.+[\n\r]*\*{3}/)
Thanks everyone for your help!

Use \\n instead of \n i tried on my code and it is working fine

Related

How can I append more html content inside append method in jQuery [duplicate]

Is \n the universal newline character sequence in JavaScript for all platforms? If not, how do I determine the character for the current environment?
I'm not asking about the HTML newline element (<BR/>). I'm asking about the newline character sequence used within JavaScript strings.
I've just tested a few browsers using this silly bit of JavaScript:
function log_newline(msg, test_value) {
if (!test_value) {
test_value = document.getElementById('test').value;
}
console.log(msg + ': ' + (test_value.match(/\r/) ? 'CR' : '')
+ ' ' + (test_value.match(/\n/) ? 'LF' : ''));
}
log_newline('HTML source');
log_newline('JS string', "foo\nbar");
log_newline('JS template literal', `bar
baz`);
<textarea id="test" name="test">
</textarea>
IE8 and Opera 9 on Windows use \r\n. All the other browsers I tested (Safari 4 and Firefox 3.5 on Windows, and Firefox 3.0 on Linux) use \n. They can all handle \n just fine when setting the value, though IE and Opera will convert that back to \r\n again internally. There's a SitePoint article with some more details called Line endings in Javascript.
Note also that this is independent of the actual line endings in the HTML file itself (both \n and \r\n give the same results).
When submitting a form, all browsers canonicalize newlines to %0D%0A in URL encoding. To see that, load e.g. data:text/html,<form><textarea name="foo">foo%0abar</textarea><input type="submit"></form> and press the submit button. (Some browsers block the load of the submitted page, but you can see the URL-encoded form values in the console.)
I don't think you really need to do much of any determining, though. If you just want to split the text on newlines, you could do something like this:
lines = foo.value.split(/\r\n|\r|\n/g);
Yes, it is universal.
Although '\n' is the universal newline characters, you have to keep in mind that, depending on your input, new line characters might be preceded by carriage return characters ('\r').
Don't use "\n". Just try this:
var string = "this\
is a multi\
line\
string";
Just enter a backslash and keep on trucking! It works like a charm.
It might be easiest to just handle all cases of the new line character instead of checking which case then applying it. For example, if you need to replace the newline then do the following:
htmlstring = stringContainingNewLines.replace(/(\r\n|\n|\r)/gm, "<br>");
Yes, use \n, unless you are generating HTML code, in which case you want to use <br />.
In an email link function, I use "%0D%0A":
function sendMail() {
var bodydata="Before "+ "%0D%0A";
bodydata+="After"
var MailMSG = "mailto:aaa#sss.com"
+ "?cc=07#sss.com"
+ "&subject=subject"
+ "&body=" + bodydata;
window.location.href = MailMSG;
}
HTML
Contact Us
You can use `` quotes (which are below the Esc button) with ES6. So you can write something like this:
var text = `fjskdfjslfjsl
skfjslfkjsldfjslfjs
jfsfkjslfsljs`;
Get a line separator for the current browser:
function getLineSeparator() {
var textarea = document.createElement("textarea");
textarea.value = "\n";
return textarea.value;
}
A note - when using ExtendScript JavaScript (the Adobe Scripting language used in applications like Photoshop CS3+), the character to use is "\r". "\n" will be interpreted as a font character, and many fonts will thus have a block character instead.
For example (to select a layer named 'Note' and add line feeds after all periods):
var layerText = app.activeDocument.artLayers.getByName('Note').textItem.contents;
layerText = layerText.replace(/\. /g,".\r");
printAccountSummary: function()
{return "Welcome!" + "\n" + "Your balance is currently $1000 and your interest rate is 1%."}
};
console.log(savingsAccount.printAccountSummary()); // Method
Prints:
Welcome!
Your balance is currently $1000 and your interest rate is 1%.
I had the problem of expressing newline with \n or \r\n.
Magically the character \r which is used for carriage return worked for me like a newline.
So in some cases, it is useful to consider \r too.
I believe it is -- when you are working with JavaScript strings.
If you are generating HTML, though, you will have to use <br /> tags (not \n, as you're not dealing with JavaScript any more).
A practical observation... In my Node.js script I have the following function:
function writeToLogFile (message) {
fs.appendFile('myserverlog.txt', Date() + " " + message + "\r\n", function (err) {
if (err)
throw err;
});
}
First, I had only "\n", but I noticed that when I open the log file in Notepad, it shows all entries on the same line. Notepad++, on the other hand, shows the entries each on their own line. After changing the code to "\r\n", even Notepad shows every entry on its own line.
The \n is just fine for all cases I've encountered. If you are working with web, use \n and don't worry about it (unless you have had any newline-related issues).
You can use <br/> and the document.write/ and document.writeln one.

Replace line end with line end + double quote javascript

I started something that appeared pretty easy, but it worked out differently.
I have this string, read from a file:
"columns:[
{
allowNull:false,
I want to replace the newline with a newline and a double-quote.
so I do:
text = text.replace(/\r?\n/g, '\n"')
somehow, the output is this:
"columns:[
\"{
\"allowNull:false,
I'm completely puzzled as to where the extra '\' is coming from. If I use a single-quote, or another character, it works just fine
What is going on here?
Within here
text = text.replace(/\r?\n/g, '\n"')
you replace with \n" instead of \n. As #vlaz indicates correctly in the comments, text.replace does not escape " to \". But the print function does.
Anyway, there's a " which may be not intended.

Parser: How to Turn a JavaScript String into One Line of JavaScript?

I'm trying to make a parser for formatting JavaScript in a contextual format. First I want to be able to convert the input JavaScript into one line of JavaScript and then format the code based on my requirements. This does not remove all of the enters or white space:
txt = $.trim(txt);
txt = txt.replace("\n", "");
How can I convert the text into one line?
Use a regular expression with the "global" flag set:
txt.replace(/\n/g, "");
However, you should be careful about removing linebreaks in Javascript. You might break code that was depending on semicolon insertion. Why don't you use an off-the shelf parser like Esprima?
Use :
\s character that represents any space character (Carriage return, Line Feed, Tabs, Spaces, ...)
the "greedy" g flag.
var text = txt.replace(/\s+/g, ' ');
Hope it helps
If the text comes from some operating systems, it may have the \r\n line ending, so it is worth removing both...
You should also use /\r/g this replaces ALL \rs not just the first one.
var noNewLines = txt.replace(/\r/g, "").replace(/\n/g, "");
You have to be pretty sure there are no single-line comments and that there are no missing semi-colons.
You can try to minify your code, using something like https://javascript-minifier.com/
however this will also change your variable names

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

Passing an escaped String to JQuery($)-Function

currently I am trying to highlight elements on a page. Therefore I pass a comma seperate String to a Javascript-Funktion called highlight.
highlight("main:box1,main:box2");
This was working fine till I found ids with : on the page. So I tried to escape them with a little regex. Here things started to get a little funny.
If I escape the string by replacing : with \: the jQuery-Function does not work anymore.
var string = value.replace(/:/g, "\\\\:");
jQuery("#" + string).css("color", "red");
If I replace main: with "" and write main\: in the jQuery-Function everything works fine.
var string = value.replace(/main:/g, "");
jQuery("#main\\:" + string).css("color", "red");
What am I doing wrong? Why does the jQuery-Function not except my escaped string?
Help needed :-(
Example-Code attached: http://db.tt/0FLRlM
Thanks Jan
You're double escaping the \ in your first attempt at substitution. What you've done is replace : with \\:, even though you're probably seeing \: when you output it.

Categories