Strip quotes with JS to convert into JSON object [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Not sure how to address this with JavsScript to convert it into a json object to pull the below content, strip the first set of quotes so it becomes a valid JSON.
"{""title"": ""Glasses"",""desc"": ""Wood Custom Build""}"
Any ideas would be appreciated.
Thanks

Before anything, here's a straightforward solution. Each string method is easily google-able if not clear.
const string = `"{""title"": ""Glasses"",""desc"": ""Wood Custom Build""}"`
console.log(string)
// remove first and last
const spliced = string.substring(1, string.length-1)
console.log(spliced)
// replace double double quotes "" with single double quotes "
const replaced = spliced.replace(/""/gi, `"`)
console.log(replaced)
// parse as JSON
const json = JSON.parse(replaced)
console.log(json)
But to go into a bit more details, it depends! Based on the source of this string and what you need out of it, it might be useful to know that JSON keys can indeed have double-quotes " in their names. But the proper way to write it would be:
{ "\"yo\"": 42 }
If you DO need to keep the extra quotes (maybe because they are identifying strings that you have no hand over), then parsing this faulty JSON is more complicated because an opening quote "\" becomes different from a closing one \"".
const string = `"{""title"": ""Glasses"",""desc"": ""Wood Custom Build""}"`
// remove first and last
const spliced = string.substring(1, string.length-1)
console.log(spliced)
// find pairs of double-quotes followed by (some optional space and) : or , or }
const closingQuote = /""(?=\s*[:,}])/g
const replaced_1 = spliced.replace(closingQuote, `\\""`)
console.log(replaced_1)
// find pairs of double-quotes that we haven't replaced yet
const notClosingQuote = /(?<!\\)""/g
const replaced_2 = replaced_1.replace(notClosingQuote, `"\\"`)
console.log(replaced_2)
const json = JSON.parse(replaced_2)
console.log(json)
This method uses regex's positive lookahead and negative lookbehind. IIRC they are somewhat new-ish features in the JS implementation of regex syntax.

Related

Regex, how to detect value in double curly braces? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 10 months ago.
Improve this question
Sorry i can't speak english :(
I write Supplant I have a regex
({{([']).*\2}})
needs regex to detect what is in a rectangle
I need it rigidly between {{' - '}} because there can be any character between the quotation marks (e.g. one { )
best to use it \1 because regex is more longer
Thanks for the help. Regards
This can work for you:
/\{\{'((?:(?!\{\{').)*?)'\}\}/g
\{\{' - start by matching {{'.
( ... ) - if you're writing a template engine you probably care about what's inside the curly braces and quotes. This captures the string inside the quotes so you'll be able to use it.
(?: ... ) - a non-captureing group (the value here will not be used).
(?!\{\{'). - match anything, except if we're seeing another {{'.
(?!\{\{').)*? - *? is a lazy match, so we'll stop at the first '}}
and finally, the closing '}}
as code it will looks something like this - I included a function to set the replaced value, because typically that's what you'd do in a template engine:
let s = "n {{'a{123456789}'}} n {{\"a{123456789}\"}} n {{'a{1234{{'a{12345{{'a{123456789}'}}6789}'}}56789}'}} ";
s = s.replace(/\{\{'((?:(?!\{\{').)*?)'\}\}/g, (wholeMatch, capturedKey) => {
console.log('captured key:', capturedKey);
return "REPLACED " + capturedKey;
});
console.log(s);
if you want to support double quotes it becomes a bit more complicated:
s = s.replace(/\{\{(["'])((?:(?!\{\{["']).)*?)\1\}\}/g,
(wholeMatch, quote, capturedKey) => { ... }
);
Try this:/(?<={{')(?!.+?{{)[^']+/gm
This basically looks for the {{' which doesn't have any other {{ in front of it then, matches everything till the first '.
Test here: https://regex101.com/r/rw6kkP/2
var myString = `{{'a{content 1}a'}}
{{'a{every{{'a{everysign}a'}}sign}a'}}
{{'a{every{{'a{every{{'a{inside content}a'}}sign}a'}}sign}a'}} `;
var myRegexp = /(?<={{')(?!.+?{{)[^']+/gm;
console.log(myString.match(myRegexp))
// [ "a{content 1}a", "a{everysign}a", "a{inside content}a" ]

How to match numbers followed by any combination of special characters and spaces using regex [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed last year.
Improve this question
I am a newbie with regex and I am having trouble trying to match some parts of a string so I can remove it from a piece of entered text. I want to match digits followed by a sequence of a combination of any special characters + spaces. There could also be non Latin characters that should not be removed inside the sequence (for example Ñ).
for example inputted it may look like:
11#- &-.text
11 $ab*cÑ .somewords123
outputted I would expect
text
abcÑsomewrods123
I am using javascript replaceall method with regex to find it. So far I have something basic like this regex
.replaceAll(/\d+(\#|\s)+(\-|\$)+(\s|\&)+(\&)+(\-)+(\.)/g, '');
Is there a way to write this more efficiently so that it captures any special characters since the text can contain more different special chars than in the examples? Or is this a situation better handled with pure JS?
Thanks in advance for your help.
You should ether have blacklist of what you calling special characters, or whitelist of the allowed characters.
for blacklist it gonna look like:
const blacklist = "!##$%^&*()_+.";
const exampleInputs = [
"te&*st+_1.",
"te%%st^*2",
"t###es*(*(*t3"
];
function removeSpecialChars(str) {
const reg = new RegExp(`[${blacklist}]`, "g");
return str.replace(reg, "");
}
exampleInputs.forEach(input => console.log(removeSpecialChars(input)));
for whitelist it gonna looks like:
const whitelist = "0-9a-zA-Z";
const exampleInputs = [
"te&*st+_1.",
"te%%st^*2",
"t###es*(*(*t3"
];
function removeSpecialChars(str) {
const reg = new RegExp(`[^${whitelist}]`, "g");
return str.replace(reg, "");
}
exampleInputs.forEach(input => console.log(removeSpecialChars(input)));

javascript code on how can I include newLine after .split [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I wrote a small function to split a string stored in variable data,
var data = "Apple|Banana";
var _res = data.split('|');
After printing _res on the console, it is Printing as Apple,Banana.
I am looking for an output where each String is printed on a newline, like,
Apple
Banana
your variable _res is an Array because it was created after splitting data. Hence it is getting printed as it is.
If you want a newline print, you need to manually do it. See below Code as an example.
Use case when you want to iterate over your input:
var data = 'Apple|Banana'; //Assuming your data variable
var _res = data.split('|');
_res.forEach(function(element) {
console.log(element);
});
Use case when you just want to test in console and alert:
var data = 'Apple|Banana'; //Assuming your data variable
var _res = data.split('|').join('\n');
alert(_res);
console.log(_res);
It sounds like you want the output as a string, in which case you shouldn't use split (which returns an array), but .replace - replace all |s with newlines:
const res = 'Apple|Banana'.replace(/\|/g, '\n');
console.log(res);
Or, with alert:
const res = 'Apple|Banana'.replace(/\|/g, '\n');
alert(res);
You should check Escape notation. You can encode special character which will have special meaning in string.
\n is used to create line breaks in string.You can split() string by , and join() by \n.
let str = 'Apple,Banana'
let newStr = str.split(',').join('\n')
console.log(newStr);
let str = 'Apple,Banana'
document.querySelector('div').innerHTML = str.split(',').join('<br>')
<div><div>
If my understanding to your problem is correct, you want to split the string using "|" and "," characters. In that case you can use pass regex value in your split method parameter.
var _res = d.data.split(/[,|]+/);
You can use this site to generate your regex https://www.regextester.com/

split a string with comma and colon [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have a string like as shown below:
var String = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:some string without comma,xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:some string,with comma,xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:some string,xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:some string without comma,xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:some string , with comma,xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:String,with comma"
Where xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx represents an alphanumeric generated Id and after the colon is a string related to that Id.The string can be a string with comma or without comma.What I wanted was that I wanted to split the string such that I get an array with ID:its corresponding string , just like shown below.
["xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:some string without comma","xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:some string,with comma","xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:some string","xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:some string without comma",
"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:some string , with comma","xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:String,with comma"]
HOW I ACCOMPLISHED THIS
I used the javascript split function where i split the string by comma followed by 36 characters (for ID) and colon.
String.split(/,(?=.{36}:)/);
PS: I apologize as previously I was not able to ask the question in the correct manner.Hope this time people understand it.
You could use String#split by comma and a look ahead for numbers and colon.
var x = "123456:a,b,c,435213:r,567876:e,363464:t,y,u";
array = x.split(/,(?=\d+:)/);
console.log(array);
For alphanumeric values
var x = "1A3456:a,b,c,43Y213:r,567W76:e,363x64:t,y,u";
array = x.split(/,(?=[a-z0-9]+:)/i);
console.log(array);
You can use the method .split(). I used the "$" as a split sign instead of "," because i thought you would like to keep them.
var values = "123456:a,b,c$435213:r$567876:e$363464:t,y,u".split("$");
var x = values[0];
console.log(values)

import data from Excel /CSV file to in angularjs json object [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I am trying to have a user upload an Excel /CSV file from their computer then convert it to JSON. I am needing these files as JSON. I have it so they can upload a CSV to JSON. Now I am wanting Excel /CSV to JSON. Any advice or guidance on this would be appreciated. This needs to be done using angularJS. Thanks!
You are going to have to read the data in however you want (File Reader, Ajax call, etc.) and then parse the data using Regular Expressions. Then when you have a string, use JSON parse
this isn't my code but here is a snippet of the linked jsfiddle
function CSVToArray(strData, strDelimiter) {
// Check to see if the delimiter is defined. If not,
// then default to comma.
strDelimiter = (strDelimiter || ",");
// Create a regular expression to parse the CSV values.
var objPattern = new RegExp((
// Delimiters.
"(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +
// Quoted fields.
"(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +
// Standard fields.
"([^\"\\" + strDelimiter + "\\r\\n]*))"), "gi");
// Create an array to hold our data. Give the array
// a default empty first row.
var arrData = [[]];
// Create an array to hold our individual pattern
// matching groups.
var arrMatches = null;
// Keep looping over the regular expression matches
// until we can no longer find a match.
while (arrMatches = objPattern.exec(strData)) {
...
http://jsfiddle.net/sturtevant/AZFvQ/

Categories

Resources