Manipulate (str.replace) array data that comes back over autocomplete - javascript

$('#groupnamesearch').blur(function () {
str = $('#groupnamesearch').val()
$.get("injectgroup.php", {
name: str
}, function (data) {
//here i guess str.replace data
$('#aspecforgroup').val(data);
});
});
This gives me results like: ["45054","55905","42306"]
I'd like to strip all []" of them, so I have only numbers and the , character.
How can I manipulate the data that came over the ajax request before it's getting populated in an input field?
Thanks :)

If the result that you are getting back in data is an actual string - and I assume it must be if the square brackets are getting displayed in your "aspecforgroup" field - then you can remove those characters as follows:
data = data.replace(/[\[\]"]/g, "");
Or you can tell jQuery (that is jQuery that you're using?) to treat the response as JSON in which case it should be automatically parsed into an array by the time it ends up in the data parameter and then you can use the array .join() method to turn that into a string:
$.get("injectgroup.php", {
name: str
}, function (data) {
$('#aspecforgroup').val(data.join(","));
}, "json");
The parameter to .join() is the string to join the individual elements with. If you leave it out it will be a comma by default, but you might want to use a comma plus a space: .join(", ").

You can do this with array join
if your data is string, you have to first parse the string to convert an array and then do a join like this -
var newData = JSON.parse(data).join();

if data is a string:
data = '["45054","55905","42306"]';
var output​ = JSON.parse(data).join(', ');
​alert(output)​;
if data is already an array:
data = ["45054","55905","42306"];
var output = data.join(', ');
alert(output);
both output this:
45054, 55905, 42306

Related

data stored as a backslash in javascript console

This is my JS code
add = document.getElementById("add");
add.addEventListener("click", () => {
console.log("Updating List...");
tit = document.getElementById("title").value;
desc = document.getElementById("description").value;
if (localStorage.getItem("itemsJson") == null) {
itemJsonArray = [];
itemJsonArray.push([tit, desc]);
localStorage.setItem("itemsJson", JSON.stringify(itemJsonArray));
}
});
The data should be [ABCD, XYZ]
but it is showing "[[\"\",\"\"]]".
The back slashes are supposed to be there. What you are looking at is a JSON encoded value. They are escaping the double-quotes that are inside the double-quoted string. eg: "This \"string\" value contains quotes".
JavaScript knows how to build the original data structure from that string (using the values shown from the screenshot in your comments)..
var items = localStorage.getItem("itemsJson");
\\ items[0] value is "s"
\\ items[1] value is "d"
I could write the following line of code and get the same result:
var items = "[[\"s\",\"d\"]]";
the JSON string value, eg "[[\"s\",\"d\"]]", starts and ends with quotes and the array that is being serialized contains the string values "s" and "d". If the array contained a number value, eg: 1, as well then the JSON encoded string would look like this:
"[[\"s\",\"d\",1]]"
If you run the following line of code:
alert("This \"string\" value contains quotes");
You would see this message: This "String" value contains quotes and illustrates the same concept of what the backslashes are doing.

Split a string into a list of strings

I have an input Json string like this:
var x= "[{\"name\":\"ahmed\",\"age\":\"26\"},
{\"name\":\"Sam\",\"age\":\"25\"}]"
I want to split it to a list of strings from{ to } as follows without removing a delimiter
var list;
list[0]= {\"name\":\"ahmed\",\"age\":\"26\"}
list[1]= {\"name\":\"Sam\",\"age\":\"25\"}
using the split method removes the delimiter and does not yield the correct format
x= x.replace(/\[\/]/g, '/'); //to remove [ and ]
x= x.replace( /},/ ,'}\n' ); // does not split the string to list of strings
list = x; // type mismatch error since x is a string and list is array
As commented above by Teemu, using JSON.parse is the safe and correct way to parse json.
const x = "[{\"name\":\"ahmed\",\"age\":\"26\"},{\"name\":\"Sam\",\"age\":\"25\"}]";
console.log(JSON.parse(x));
You can parse it to JSON first then use map to make list out of it.
var parsedX = JSON.parse(x);
var list = parsedX.map(x => JSON.stringify(x).replace(/"/g,'\\"'));
You could use following code to achieve desired result with this particular type of json:
var str = "[{\"name\":\"ahmed\",\"age\":\"26\"}, {\"name\":\"Sam\",\"age\":\"25\"}]";
var list = str.match(/[{][^{}]*[}]/gm);
alert(list)
Fell free to ask if you have any questions:

Read value from string which looks like jSon format

I have cookie value stored in following format
{stamp:'HMzWoJn8V4ZkdRN1DduMHLhS3dKiDDr6VoXCjjeuDMO2w6V+n2CcOg==',necessary:true,preferences:true,statistics:true,marketing:false,ver:1}
and i need to read following values of
necessary
preferences
statistics
marketing
Not sure how to to read values correctly, i tried following code assuming it is jSON format
Cookies.get('CookieConsent')
//Parse the cookie to Object
cookieval = Cookies.get('CookieConsent');
console.log(cookieval);
console.log("Necessary: " + Boolean(cookieval.necessary));
console.log("Prefrences: " + Boolean(cookieval.preferences));
console.log("Statistics: " + Boolean(cookieval.statistics));
console.log("Marketing: " + Boolean(cookieval.marketing));
But this code always returns false.
I use following Jquery to read Cookie values https://cdn.jsdelivr.net/npm/js-cookie#2/src/js.cookie.min.js
You do not have JSON format - you have something closer to JS object literal notation, except that it's a string rather than JS code, so can't use JSON.parse unfortunately.
If the values don't have commas or colons, you can split the string by commas and reduce into an object:
const input = `{stamp:'HMzWoJn8V4ZkdRN1DduMHLhS3dKiDDr6VoXCjjeuDMO2w6V+n2CcOg==',necessary:true,preferences:true,statistics:true,marketing:false,ver:1}`;
const obj = input
.slice(1, input.length - 1)
.split(',')
.reduce((obj, str) => {
const [key, val] = str.split(':');
obj[key] = val;
return obj;
}, {});
console.log(obj);
eval is another option, but that's unsafe.
Wrap this string by ( and ). Then parse like as display follow
Attention! But you need be ensure input string (which received from cookie) not contains bad code. Such as unknown injected function. In this case, the function will be executed on client browser, with access to private data (cookie, localStorage, data from html-forms).
const input = "{stamp:'HMzWoJn8V4ZkdRN1DduMHLhS3dKiDDr6VoXCjjeuDMO2w6V+n2CcOg==',necessary:true,preferences:true,statistics:true,marketing:false,ver:1}"
const object = eval("(" + input + ")");
alert(object.necessary);
What about massaging the string into proper JSON, parsing it into a JSON Object, and using the fields from there?
It's less stable in that changes to the input string may break the function, but it is secure in that it's calling JSON.parse() rather than eval().
function reformatCookieInput(inputString) {
inputString = inputString.replace(/'/g, ""); //global strip out single quotes currently wrapping stamp
inputString = inputString.replace(/,/g, `", "`); //global replace commas with wrapped commas
inputString = inputString.replace(/:/g, `":"`); //same idea with colons
inputString = inputString.replace("{", `{"`); //rewrap start of JSON string
inputString = inputString.replace("}", `"}`); //rewrap end of JSON string
return inputString;
}
const input = `{stamp:'HMzWoJn8V4ZkdRN1DduMHLhS3dKiDDr6VoXCjjeuDMO2w6V+n2CcOg==',necessary:true,preferences:true,statistics:true,marketing:false,ver:1}`;
const properJSONObject = JSON.parse(reformatCookieInput(input));
console.log(properJSONObject);

How to convert array which is in string format to array of object?

I have an array of objects which is a string.
[{
'version_name': '1.4',
'url': 'url'
},
{
'version_name': '1.3',
'url': 'url'
},
{
'version_name': '1.2',
'url': 'url'
},
{
'version_name': '1.1',
'url': 'url'
}]
I am using this code to remove all the space:
str = str.replace(/\s+/g, '');
Now, I want to convert it to proper array of objects. How do i do that?
I tried string.split() which kind of works but each array element becomes a string instead of an object.
If you control the source of the string, the best thing would be to modify the source so that it creates valid JSON (" instead of ' on property keys and strings).
If you can't change the source of it and have to deal with that string, you have a couple of options:
Replace the ' with " and use JSON.parse, since that text is valid JSON other than that it uses ' instead of " and it doesn't appear to use ' for anything else:
var result = JSON.parse(theText.replace(/'/g, '"'));
Live Example:
var theText = "[{'version_name':'1.1','url':'value'}, {'version_name':'1.2','url':'value'}, {'version_name':'1.32','url':'value'}, {'version_name':'1.4','url':'value'}]";
var result = JSON.parse(theText.replace(/'/g, '"'));
console.log(result);
Your other option, if you trust the source of that text, is to use eval, since the quoted text is valid JavaScript object initializer syntax.
// ONLY IF YOU CAN ABSOLUTELY TRUST THE SOURCE OF THAT TEXT
var result = eval(theText);
Live Example:
var theText = "[{'version_name':'1.1','url':'value'}, {'version_name':'1.2','url':'value'}, {'version_name':'1.32','url':'value'}, {'version_name':'1.4','url':'value'}]";
var result = eval(theText);
console.log(result);
A JSON string expects key and value to be wrapped in double quotes and not in single. But replacing every single quote can be incorrect as it can be a part of value. So you can pass string through series of regex to make it in correct format.
Sample:
var str = "[{'invalid_value': 'foo's','version_name': '1.4','url': 'url'} , {'version_name': '1.3','url': 'url'},{'version_name': '1.2','url': 'url'},{'version_name': '1.1','url': 'url' }]";
function parseObj(str) {
str = str.replace(/\'\s*:\s*\'/g, '":"');
str = str.replace(/\'\s*,\s*'/g, '","');
str = str.replace(/{\s*\'/g, '{"');
str = str.replace(/\'\s*}/g, '"\}');
return JSON.parse(str);
}
console.log(parseObj(str))
you can use json parse: const arr = JSON.parse(yourString.replace(/'/g, '"')))

Split a string in javascript not working

I have a function where I get some values dynamically and I send them to other function.
function sample(){
//some code here
var latlong1=//some value;
var latlong2=//some value;
fnSplitString(latlong1,latlong2);
}
I am sending these values to a function say
function fnSplitString(l1,l2)
{
alert("Latlong1::::"+l1);
alert("LatLong2::::"+l2);
var splitStringLatLong=l1.split(",");
alert("split1"+splitStringLatLong[0]);
alert("split2"+splitStringLatLong[1]);
}
here my 'l1' and 'l2' are alerting the values properly as.
Latlong1::::lat=78.23456,long=26.56789
Latlong2::::lat=74.57585,long=22.67890
I want to extract only the numeric values from these two strings. Hence I tried splitting it first till comma. But the split is not working at all. I do not get any alert message. Where is the mistake? And how do I extract only numeric from the string?
There is an extra semi-colon at the end of the first line of your fnSplitString definition.
Try removing that and see if it works. Corrected code below.
function fnSplitString(l1,l2)
{
alert("Latlong1::::"+l1);
alert("LatLong2::::"+l2);
var splitStringLatLong=l1.split(",");
alert("split1"+splitStringLatLong[0]);
alert("split2"+splitStringLatLong[1]);
}
It's not the best solution but this works:
var temp = 'lat=78.23456,long=26.56789';
var lat = temp.substring(4, temp.indexOf(",long"));
var long = temp.substring(temp.indexOf("g")+2, temp.length);
alert(lat);
alert(long);
I think regex is the simplest solution.
I'm not very strong in this, but here goes:
var str = "lat=78.23456,long=26.56789";
var s = str.match(/(?:\d*\.)?\d+/g);
alert("string1: "+s[0]+", string2: "+s[1]);
The result is an array of strings, but you can convert it to whatever you want.

Categories