How to create whitespace inside a JSON - javascript

I want to put a line of space or blanks between the values. Because they're all leaving together right now.
My example:
data: JSON.stringify({
"sessionID":xxxxx,
"synchronize":false,
"sourceRequest":{
"numberOrigin":xxxxxx,
"type":"x",
"description":test + "\\n" + test2 "\\n" + test3 "\\n" + test4,
"userID":xxxxxxxx,
"contact":{
"name":"xxxxxxxxxxxxxxxxx",
"phoneNumber":"xxxxxxxxxx",
"email":xxxx,
"department":"xxxxx"
},

The "\\n" says to put a literal \n in the string - 2 chars. You should just use "\n" to say that its a new line - 1 char.
Note if viewing in Windows Notepad, \n is not enough for a new line.

A simple ' ' (space character) is enough to do what is needed, the json key does hold a string after all, if you need something more prominent you can use '\t', refer here for more.

Related

How do I properly escape and unescape a multiline string that contains newline literals?

I'm working on a Visual Studio Code extension. The extension is supposed to act on the text that is currently selected in the editor window and send it to an external command (lein-cljfmt in my case, but I think that's unrelated to my question). When the external command is done processing the text I want to replace the current editor selector with the result returned from the command line tool.
Before sending the string I escape it like this:
contents
.replace(/\\/g, '\\\\')
.replace(/"/g, '\\"')
.replace(/\n/g, '\\n');
The result in being unescaped like:
contents
.replace(/\\n/g, '\n')
.replace(/\\"/g, '"')
.replace(/\\\\/g, '\\');
This works in all but one case: when the selection that is being processed contains a string literal that contains a newline literal, the unescaping will instead turn this into a linebreak, thus breaking the code in the editor.
This is an example of a snippet that breaks my escaping:
(defn join
[a b]
(str a "\n" b))
I tried quite some regexp black magic like
.replace(/(?!\B"[^"]*)\\n(?![^"]*"\B)/g, '\n')
by now, but couldn't find a solution that does not have edge cases. Is there a way to do this that I am missing? I also wonder if there is a VSCode extension API that could handle that as it seems to be a common scenario to me.
I think this might be what you need:
function slashEscape(contents) {
return contents
.replace(/\\/g, '\\\\')
.replace(/"/g, '\\"')
.replace(/\n/g, '\\n');
}
var replacements = {'\\\\': '\\', '\\n': '\n', '\\"': '"'};
function slashUnescape(contents) {
return contents.replace(/\\(\\|n|")/g, function(replace) {
return replacements[replace];
});
}
var tests = [
'\\', '\\\\', '\n', '\\n', '\\\n', '\\\\n',
'\\\\\n', '\\\\\\n', '\\"\\\\n', '\n\n',
'\n\n\n', '\\n\n', '\n\\n', '\\n\\n',
'\\\n\\n\nn\n\\n\\\n\\\\n', '"', '\\"', '\\\\"'
];
tests.forEach(function(str) {
var out = slashUnescape(slashEscape(str));
// assert that what goes in is what comes out
console.log(str === out, '[' + str + ']', '[' + out + ']');
});
Trying to unescape the string in 3 stages is really tricky because \n has a different meaning depending on how many slashes there are just before it. In your example the original string of \n (slash n) gets encoded as \\n (slash slash n), then when you decode it the last two characters match the first of your RegExps when what you want is for the first two characters to match the third RegExp. You've got to count the slashes to be sure. Doing it all in one go dodges that problem by decoding those leading slashes at the same time.

On JavaScript regex alternation and character sets

Maybe I'm stupid, but this problem really got me baffled.
var text = "aaa\naaa\naaa";
console.log("A: " + text.match(/(.|[\r\n])+/)[0]);
console.log("B: " + text.match(/[\r\n.]+/)[0]);
Output:
A: aaa
aaa
aaa
B:
I really don't see why. I think they should do the same thing (besides grouping stuff).
Another question which might be related:
I have a string read from a file created in a Windows system. I tried to match everything.
/[\n\r.]+/ matches the entire string.
/[\n\r.]+/g does not (I got a lot of '\r\n' in the returned array).
but both /[\s\S]+/ and /[\s\S]+/g matches the entire string.
What's the problem?
(.|[\r\n]) this pattern means any charcter | carriage return/new line
[\r\n.] this one means carriage return/new line/literal dot

insert line break in tweet from URL?

So I have a script like this now:
popUp("https://twitter.com/intent/tweet?text=" + greeting + poem + " -&url=" + siteURL, 704, 260);
The "poem" is a haiku and I'd love to have it like:
line1
line2
line3
rather than line 1 // line 2 // line 3, which it is now. I tried inserting stuff like \n in there to no avail. "Poem" is constructed simply like line1 + " // " + line2 ...
As you've guessed, newline characters cannot appear in URLs.
Using a random escaping mechanism won't do you any good; you need to URL-encode the newline:
https://twitter.com/intent/tweet?text=abc%0adef
Creates a line break on twitter if you're posting from the HTML form. You'll need to remove the spaces in bewteen the characters, I couldn't figure out how to make the answer not escape to a newline. Irony alert

Regular expression for removing whitespaces

I have some text which looks like this -
" tushar is a good boy "
Using javascript I want to remove all the extra white spaces in a string.
The resultant string should have no multiple white spaces instead have only one. Moreover the starting and the end should not have any white spaces at all. So my final output should look like this -
"tushar is a good boy"
I am using the following code at the moment-
str.replace(/(\s\s\s*)/g, ' ')
This obviously fails because it doesn't take care of the white spaces in the beginning and end of the string.
This can be done in a single String#replace call:
var repl = str.replace(/^\s+|\s+$|\s+(?=\s)/g, "");
// gives: "tushar is a good boy"
This works nicely:
function normalizeWS(s) {
s = s.match(/\S+/g);
return s ? s.join(' ') : '';
}
trims leading whitespace
trims trailing whitespace
normalizes tabs, newlines, and multiple spaces to a single regular space
Try this:
str.replace(/\s+/g, ' ').trim()
If you don't have trim add this.
Trim string in JavaScript?
Since everyone is complaining about .trim(), you can use the following:
str.replace(/\s+/g,' ' ).replace(/^\s/,'').replace(/\s$/,'');
JSFiddle
This regex may be useful to remove the whitespaces
/^\s+|\s+$/g
Try:
str.replace(/^\s+|\s+$/, '')
.replace(/\s+/, ' ');
try
var str = " tushar is a good boy ";
str = str.replace(/^\s+|\s+$/g,'').replace(/(\s\s\s*)/g, ' ');
first replace is delete leading and trailing spaces of a string.

JavaScript Replace - u0009 .... with .replace(/\u0009/g,'');

I'd like to use Javascript to replace all instances of \u009 in a string
This doesn't seem to be working: .replace(/\u0009/g,'');
Do I need to escape something?
First, the question says "replace all instances of \u009 in a string".
But, the regex has replace(/\u0009/g,''); Is this a typo (different number of zeroes)?
Anyway, if the string only contains, unicode, horizontal tab characters (just one char), then the regex is fine.
If it actually contains 6 ascii chars, then the regex needs to be escaped, like so:
var oneChar = 'Pre \u0009 post';
var sixChars = 'Pre \\u0009 post';
//-- NOTE: If not using Firebug, replace 'console.log()' with 'alert()'.
console.log (oneChar + ' becomes --> ' + oneChar.replace (/\u0009/g, "") );
console.log (sixChars + ' becomes --> ' + sixChars.replace (/\\u0009/g, "") );
You need another escape .replace(/\\u009/g,''); :)

Categories

Resources