Convert string array to array in javascript - javascript

I get the following item back from my django-rest-framework api call:
services = "['service1', 'service2', 'service3']"
I want services = ['service1', 'service2', 'service3']
In my JavaScript I tried services = JSON.parse(services)
- didn't do anything, also tried $.parseJSON(services).
In my serializers I have tried the setting services as ListField, also tried JSONSerializerField()
class JSONSerializerField(serializers.Field):
# Adapted from http://stackoverflow.com/a/28200902
def to_internal_value(self, data):
return json.loads(data)
def to_representation(self, value):
return value

To parse it you need to use double quotes instead of single.
This should work:
services = '["service1", "service2", "service3"]'
JSON.parse(services)

This is used to convert string which is array into pure array
var a = '[Aakash,akash]'
a.replace(/\[|\]/g,'').split(',')
(2) ["Aakash", "akash"]

Your response is of the form
services = "['service1', 'service2', 'service3']"
JSON.parse() will work if the parent quote is a single quote and all other child quotes are double quotes. I have quoted an example below
services = '["service1", "service2", "service3"]'
We can use replace() to achieve this
Here is a working example
services = "['service1', 'service2', 'service3']"
services = services.replace(/'/g, '"') //replacing all ' with "
services = JSON.parse(services)
console.log(services)

To ensure correct parsing between Django and some javascript browser code, be sure that you return a JsonResponse() in your controller. This ensures you can parse it with JSON.parse() in your Javascript.

Try Using:
var services = "['service1', 'service2', 'service3']"
services = services .split(",");
services [0] = services [0].substring(1);
services [services .length - 1] = services [services .length - 1].substring(
0,
services [services .length - 1].length - 1
);
services .forEach((x, i) => {
services [i] = services [i].includes('"') ? services [i].replaceAll('"', "").trim()
: services [i].replaceAll("'", "").trim();
});
console.log(services );

I recently found a roundabout way of solving a similar problem. I wanted to store an array as a data attribute in an HTML element so that I could use it later in the JS. However, such an HTML attribute could only be stored as a string. To solve this...
First I turned the arrays into a single string, with each value separated by a comma (ex. ["test 1", "test 2", "test 3"] is written as “test 1,test 2,test 3”).
Next, I entered the new string into the desired HTML data attribute. (ex. <div data-somedata="test 1,test 2,test 3"></div>)
Upon entering the JS, I retrieved that data string and converted it back into an array by using jQuery's "split” method. For this check out the snippet here.
let stillString = $("[data-something]").attr('data-something');
console.log(stillString);
let nowArray = stillString.split(",");
console.log(nowArray);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-something="test 1,test 2,test 3"></div>
This may not look pretty, keeping an array as a string, but it gets the job done and your average users won't know the difference.
NOTE: You don't HAVE to use commas. You could use any character really. The only thing that matters that none of the values that you're trying to separate contain the character that you chose split them with.

Related

Array to Newline String to Array again through HTML

I have an array that comes in from from my API that I would like to arrange in a way that is better for the user (namely, in a column as opposed to the typical comma separated printed array).
This is my JS Fiddle to give a clearer picture: https://jsfiddle.net/2z89owas/
My question is, how can I get output3 to display just like output (and maintain its status as an iterable array like it was as dates)?
First you should not be using value for an html element. You can use .value for extracting value from inputs. Change your line to:
var val = document.getElementById('output2').innerHTML;
Afterwards, you have to split the same way you did join.
var dates3 = val.split('<br>');
document.getElementById('output3').innerHTML = dates3;
You can directly use join, something like:
document.getElementById('output3').innerHTML = dates.join(',');
You can try mapping over the contents of dates instead, as so:
let datesElem = dates.map(date =>`<p>${date}</p>`);
// test: console.log(datesElem)
document.getElementById('output3').innerHTML = datesElem

Javascript: How to use Template Literals with JSON?

I discovered Javascript ES6 Template Literals today. Just one word: Awesome!
Question: How to store and load Template Literals as JSON? I load some files via XHR, followed by some JSON.parse() which doesn't support ` instead of ", so it seems one can't save Template Literals directly in the files.
Goal: To use this for dynamic strings and translation and to get rid of confusing stuff like ("Hello " + username + "! How are you?") which requires multiple strings to be stored for just one message, and instead save my stuff beautifully and simple as
`Hello, ${username}! How are you?`
where username points to the dynamic variable with the same name. Is that possible? If yes, how to achieve this? It's okay if i have to use a function to somehow convert the strings into Template Literals as long as it doesn't hit hard on the overall performance, but I would like to at least avoid eval.
You can create your own function to parse template literal,
function stringTemplateParser(expression, valueObj) {
const templateMatcher = /{{\s?([^{}\s]*)\s?}}/g;
let text = expression.replace(templateMatcher, (substring, value, index) => {
value = valueObj[value];
return value;
});
return text
}
console.log(stringTemplateParser('my name is {{name}} and age is {{age}}', {name: 'Tom', age:100}));
// output 'my name is Tom and age is 100'
You could always use JSON.stringify to enclose dynamic data:
const data = 'some value';
JSON.stringify({
data,
});
// expected: "{\"data\": \"some value\"}"
I found it easier to separate the problem in a few substrings of JSON. Create the key "message" and this key stores parts of the message. It also works well for i18n.
{
"message" : {
"_0": "first part ",
"_1": "after first variable. ",
"_2": "after another variable"
}
}
And then, after decoding it, you can access it like
${message._0}${variable}${message._1}${var2}${message._2}
Try json-templates. Looks like exactly what you're looking for.

Concatenating Multiple String and Texts Together Into A String - Blogger Javascript

I have 2 questions here :
Question 1.
How to concatenate multiple text and strings into one String variable and return the string?
function TagGen()
{
var getTitle="Nidome no Jinsei wo Isekai de Chapter 1 Raw Manga";
var getTag=getTitle.substring(0, getTitle.lastIndexOf(" Chapter"));
var setTags={""+getTitle+", "+getTitle+" Raw Manga"+", "+getTitle+", "+getTag+" Raw Manga"+", "+getTag+" Raw"+", "+getTag+" Manga Download"+", "+getTag+" Download"+", "+getTag+" jcafe"+", "+getTag+" Chapter Download,"+", "+getTag+" Raw Chapters"+", "+getTag+" jcafe24"+", "+"Raw Download"+", "+getTitle+" Raw Manga Download"+", "+getTitle+" jcafe"};
return setTags;
}
I want the setTags to be have the string value something like the below,
I tried to run this code several times in Tryit Editor but didn't get setTags variable working. Please help.
Question 2.
I want to store multiple tags of my blogger blog post into one String.
I know that there must be some b:loop used but I still have not yet fully understood its uses.
Suppose I have a post with the labels : Action,Adventure,Romance,Shounen
I want it to get all those labels and store it in a String like:
labels=Action,Adventure,Romance,Shounen
The basic idea of the saving into String is same as the first question but I don't know how to get multiple tags and do it.
Please help :D
To get all the labels present in a post into a variable in a concatenated form, you can use the following code -
<script>
var labelArray = <b:eval expr='data:post.labels map (label => label.name)' />;
var labels = labelArray.join(',');
</script>
This utilizes the Lambda operator map provided by Blogger.

Using Jquery to get numeric value which is in between "/" in link

I am trying to fetch numeric value from link like this.
Example link
/produkt/114664/bergans-of-norway-airojohka-jakke-herre
So I need to fetch 114664.
I have used following jquery code
jQuery(document).ready(function($) {
var outputv = $('.-thumbnail a').map(function() {
return this.href.replace(/[^\d]/g, '');
}).get();
console.log( outputv );
});
https://jsfiddle.net/a2qL5oyp/1/
The issue I am facing is that in some cases I have urls like this
/produkt/114664/bergans-of-norway-3airojohka-3jakke-herre
Here I have "3" inside text string, so in my code I am actually getting the output as "11466433" But I only need 114664
So is there any possibility i can get numeric values only after /produkt/ ?
If you know that the path structure of your link will always be like in your question, it's safe to do this:
var path = '/produkt/114664/bergans-of-norway-airojohka-jakke-herre';
var id = path.split('/')[2];
This splits the string up by '/' into an array, where you can easily reference your desired value from there.
If you want the numerical part after /produkt/ (without limitiation where that might be...) use a regular expression, match against the string:
var str = '/produkt/114664/bergans-of-norway-3airojohka-3jakke-herre';
alert(str.match(/\/produkt\/(\d+)/)[1])
(Note: In the real code you need to make sure .match() returned a valid array before accessing [1])

How do I get the text between two characters of a string in JavaScript?

I have an array like this:
var people = [
'<option value=\'64\'>Tom',
'<option value=\'76\'>Dan',
];
I am looping through each item in the array to extract the value (like the number 64 in the first item) and the text (like Tom in the first item). I tried multiple ways of extracting these details from each item but I am unable to. I even tried using substrings and other methods. Can someone tell me how to extract this information?
You should use a regular expression in such a case.
For example:
var things = people.map(function(s){
return s.match(/(\d+)\W+(\w+)$/).slice(1)
});
This builds this array:
[ ["64", "Tom"], ["76", "Dan"] ]
You might want to adapt it for your precise needs:
check an array is returned by match, if some strings might be invalid
change the regex if the pattern is more variable
Note that you probably shouldn't have such an array to start with. If you generate it server-side, you should opt for the generation of a JSON structure instead and let the client script build the interface from the data, instead of building it from something which is neither clean data nor GUI.
You can use multiple split :
var str = '<option value=\'64\'>Tom';
var tmpStr = str.split("'");
var number = (tmpStr[1].split("\\"))[0];
var name = (tmpStr[2].split(">"))[1];
document.write(number + " " + name);

Categories