Remove new line in javascript code in string - javascript

I have a string with a line-break in the source code of a javascript file, as in:
var str = 'new
line';
Now I want to delete that line-break in the code. I couldn't find anything on this, I kept getting stuff about \n and \r.
Thanks in advance!
EDIT (2021)
This question was asked a long, long time ago, and it's still being viewed relatively often, so let me elaborate on what I was trying to do and why this question is inherently flawed.
What I was trying to accomplish is simply to use syntax like the above (i.e. multi-line strings) and how I could accomplish that, as the above raises a SyntaxError.
However, the code above is just invalid JS. You cannot use code to fix a syntax error, you just can't make syntax errors in valid usable code.
The above can now be accomplished if we use backticks instead of single quotes to turn the string into a template literal:
var str = `new
line`;
is totaly valid and would be identical to
var str = 'new\n line';
As far as removing the newlines goes, I think the answers below address that issue adequately.

If you do not know in advance whether the "new line" is \r or \n (in any combination), easiest is to remove both of them:
str = str.replace(/[\n\r]/g, '');
It does what you ask; you end up with newline. If you want to replace the new line characters with a single space, use
str = str.replace(/[\n\r]+/g, ' ');

str = str.replace(/\n|\r/g,'');
Replaces all instances of \n or \r in a string with an empty string.

Related

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'>");
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.
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 :\/.

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

Javascript regular expression to find double quotes between certain characters

I'm trying to create a string that can be parsed into JSON. The string is dynamically created based on the content in a CMS.
That content could contain HTML markup with double quotes, which confuses the JSON parser. So, I need to replace the double quotes in the HTML with " without replacing the double quotes which are actually a part of the JSON structure.
My Idea is to wrap the HTML inside markers, which I could use to identify everything between these markers as the quotes I want to replace.
For instance the string I want to parse into JSON could look like this...
str = '{"key1":"XXX<div id="divId"></div>YYY", "key2":"XXX<div id="divId"></div>YYY"}';
So, I want to replace every double quote between a XXX and a YYY with a ".
Something like...
str = str.replace(/XXX(")YYY/g, '"');
Hope that made sense. Thanks for any suggestions.
Given Stack Overflow's "we don't do your homework" principles, I don't think I'm going to work through the whole solution, but I can give you some pointers in half-finished code.
var xySearch = /this regex should find any text between XXX...YYY/g;
// note the g at the end! That's important
var result;
var doubleQuoteIndices = [];
// note the single-equals. I avoid them when possible inside a "condition" statement,
// but here it sort of makes sense.
while (result = xySearch.exec(str)) {
var block = result[0];
// inside of the block, find the index in str of each double-quote, and add it
// to doubleQuoteIndices. You will likely need result.lastIndex for the absolute position.
}
// loop backwards through str (so that left-side replacements don't change right-side indexes)
// to replace the characters at each doubleQuoteIndices with the appropriate HTML.
I kind of find that as great as regex's are for certain patterns, having the programming language do some of the work is often the best solution.

Can you create a JavaScript string without using ' or " quotes?

I have a JS file with some XML in it, where the XML is supposed to get converted to a word by the server.
E.g.
var ip = "<lang:cond><lang:when test="$(VAR{'ip_addr'})">$(VAR{'ip_addr'})</lang:when></lang:cond>";
This gets converted to:
var ip = "192.168.0.0";
However, in case the server doesn't work as intended, I don't want there to be a syntax error, and this is VERY important. Currently there would be a syntax error because the language uses both types of quotes. I can't think of a way to get around this, but perhaps there's another way to do quotes in JavaScript? Or to create a string?
For example, in Python I'd use triple quotes:
ip = """<lang:cond><lang:when test="$(VAR{'ip_addr'})">$(VAR{'ip_addr'})</lang:when></lang:cond>"""
Anyone have a bright idea?
I have had to create strings without quotes for a project as well. We were delivering executable client javascript to the browser for an internal website. The receiving end strips double and single quotes when displayed. One way I have found to get around quotes is by declaring my string as a regular expression.
var x = String(/This contains no quotes/);
x = x.substring(1, x.length-1);
x;
Using String prototype:
String(/This contains no quotes/).substring(1).slice(0,-1)
Using String.fromCharCode
String.fromCharCode(72,69,76,76,79)
Generate Char Codes for this:
var s = "This contains no quotes";
var result = [];
for (i=0; i<s.length; i++)
{
result.push(s.charCodeAt(i));
}
result
In JavaScript, you can escape either type of quote with a \.
For example:
var str = "This is a string with \"embedded\" quotes.";
var str2 = 'This is a string with \'embedded\' quotes.';
In particular, your block of JavaScript code should be converted to:
var ip = "<lang:cond><lang:when test=\"$(VAR{'ip_addr'})\">$(VAR{'ip_addr'})</lang:when></lang:cond>";
In general, I always prefer to escape the quotes instead of having to constantly switch quote types, depending upon what type of quotes may be used within.
I was looking for a solution to the same problem. Someone suggested looking at https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/template_strings which proved helpful. After reading about half the article, it stated that you can create strings with the backward tick character. (`)
Try this :)
document.getElementById('test').innerHTML = `'|'|'|"|"`
<div id="test" style="font-size:3em;"></div>
You can't create a string without using a single or double quote, as even calling the String() prototype object directly still requires you to pass it the string.
Inside XML you would use CDATA, but inside JS you'll have to just escape the '\"strings\"' "\'appropriately\'"

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

Categories