I am building a csv, I need to skip the metadata from the array which is at 1st pos
How do I get a output like
"2","3","4"
"6","7","8"
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var list = [
["meta1", "2", "3", "4"],
["meta2", "6", "7", "8"]
];
var csv = list.map(function(d) {
return '"' + d.join('","') + '"';
}).join('<br/>');
var x = document.getElementById("demo");
x.innerHTML = csv;
}
</script>
</body>
</html>
You can call shift() which remove first element from array
https://www.w3schools.com/jsref/jsref_shift.asp
Or
you can use splice().Usage is explained for example here:
How to remove element from an array in JavaScript?
Related
The below script returns the following into my html:
"3.9 °C {alarm,unackedAlarm}"
I would like to remove the "{alarm,unackedAlarm}" section so it just shows the temperature value. I believe I need to use a substring to achieve this but I cannot work out where to place it?
Thanks
<script src="https://requirejs.org/docs/release/2.3.6/minified/require.js" ></script>
require(['baja!', 'dialogs'], function (baja, dialogs) {
var sub = new baja.Subscriber();
sub.attach('changed', function(prop) {
if(prop.getName() === 'value');
{
document.getElementById("oat").innerHTML = ( this.get(prop));
}
});
baja.Ord.make('station:|slot:/BajaScriptExamples/Components/Ramp/out/value').get({ subscriber: sub});
});
'''
I would suggest using the regex approach just in case the number of characters change.
function extract(text) {
const pattern = /^(.*) {.*}$/g;
const match = [...text.matchAll(pattern)];
if (match.length == 0 || match[0].length == 0) {
console.error("text does not match");
return;
}
return match[0][1];
}
console.log(extract("3.9 °C {alarm,unackedAlarm}"));
The main idea here is to catch any string that follows this pattern (.*) {.*} and return what is in contained between the parenthesis (group).
The requirement of extracting specific part of a string can be done easily by using the split() function of Javascript.
Here are working examples using split:
Example 1: Split the string at blank spaces and print the first two parts.
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var str = "3.9 °C {alarm,unackedAlarm}"
var result = str.split(" ")
document.getElementById("demo").innerHTML = (result[0] + " " + result[1])
</script>
</body>
</html>
Example 2: Split the string at '{' and print the first part.
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var str = "3.9 °C {alarm,unackedAlarm}"
var result = str.split("{")
document.getElementById("demo").innerHTML = (result[0].trim())
</script>
</body>
</html>
Output:
3.9 °C
More information:
https://www.w3schools.com/jsref/jsref_split.asp
Trying to turn..
#one #two #three
into
one, two, three
Almost got it working but it misses the first one..
Code..
<!DOCTYPE html>
<html>
<body>
<p>Click the button to replace " #" with ", " in the paragraph below:</p>
<p id="demo">#one #two #three</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var str = document.getElementById("demo").innerHTML;
var res = str.replace(/ #/g, ", ");
document.getElementById("demo").innerHTML = res;
}
</script>
</body>
</html>
https://www.w3schools.com/code/tryit.asp?filename=GALOV6REXR1C
You can use String#replace with a callback where the function can be used to distinguish the replace value
<!DOCTYPE html>
<html>
<body>
<p>Click the button to replace " #" with ", " in the paragraph below:</p>
<p id="demo">#one #two #three</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var str = document.getElementById("demo").innerHTML;
var res = str.replace(/^#|( #)/g, (_, m1) => m1 ? ", " : '');
document.getElementById("demo").innerHTML = res;
}
</script>
</body>
</html>
I'd .match substrings that have a # right before them, and then .join by commas:
const str = '#one #two #three';
const arr = str.match(/(?<=#)\S+/g);
const output = arr.join(', ');
console.log(output);
Without lookbehind, if the hashtags are separated by spaces, split by spaces, .map to remove the first hash character from each, then join:
const str = '#one #two #three';
const output = str
.split(' ')
.map(hashtag => hashtag.slice(1))
.join(', ');
console.log(output);
I need to fetch data based upon the input received.
For example, if the input is 'Royal python', I should get details of Royal python.but with the following code, i get error saying 'The file you asked for does not exist'. But I get the value into fname. But not sure if the function is correct to fetch data from from array.Also I wanted to know if there is any shorter way to do this. Please help?
I'm using JavaScript for this, my code and the web page look are below:
<!DOCTYPE html>
<html>
<body>
<form> <input type="text" name="fname" required>
<button onclick="myFunction()">OK</button> `enter code here`
</form>
<p id="demo"></p>
<script> var text = '{"animals":[' +
'{"Common Name":"Royal Python","Order":"Squamata","Family":"Boidae","Genus":"Python","Species":"regius","Zoo":"Blackpool Zoo","Number":4 },' +
'{"Common Name":"Emperor Penguin","Order":"Sphenisciformes","Family":"Spheniscidae","Genus":"Aptenodytes","Species":"forsteri",` "Zoo":"Welsh Mountain Zoo","Number":35 },' +`
'{"Common Name":"Chimpanzee","Order":"Primates","Family":"Pongidae","Genus":"Pan","Species":"troglodytes", "Zoo":"Blackpool Zoo","Number":8 }]}';
obj = JSON.parse(text);
//function to fetch data based on input
function myFunction(fname)
{ var ani = "";
if (document.getElementByname("fname")="Royal Python")
var ani = document.getElementById("demo").innerHTML = obj.animals[0].Zoo + " " + obj.animals[0].Species; }} </body> </html>
Here is a solution to your problem that uses a for loop to check each index of the animal array for a match. This match will be case-insensitive also.
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<input type="text" name="fname" required>
<button onclick="fetchAnimal()">OK</button> `enter code here`
<script>
var animalsArr = [{
"commonName": "Royal Python",
"order": "Squamata",
"family": "Boidae",
"genus": "Python",
"species": "regius",
"zoo": "Blackpool Zoo",
"number": 4
}, {
"commonName": "Emperor Penguin",
"order": "Sphenisciformes",
"family": "Spheniscidae",
"genus": "Aptenodytes",
"species": "forsteri",
"zoo": "Welsh Mountain Zoo",
"number": 35
}, {
"commonName": "Chimpanzee",
"order": "Primates",
"family": "Pongidae",
"genus": "Pan",
"species": "troglodytes",
"zoo": "Blackpool Zoo",
"number": 8
}]
function fetchAnimal() {
var i;
var len = animalsArr.length;
// convert input name to lower-case
var name = document.getElementsByName('fname')[0].value.toLowerCase();
for (i = 0; i < len; i++) {
// check to see if lower-case input is the same as lower-case animal name (this ensures the match is case-insensitive)
if (animalsArr[i].commonName.toLowerCase() === name) {
document.getElementById('demo').innerHTML = animalsArr[i].zoo + ' ' + animalsArr[i].species;
}
}
}
</script>
</body>
</html>
Note: It is highly recommended move the JS code into an external script file if you intend to add more interactivity to the page.
There are a number of issues in your code:
document.getElementByname("fname")="Royal Python" should be document.getElementsByName("fname")[0].value == "Royal Python"
Also, it's cumbersome to write the text string and then parse it as JSON. Just use a JavaScript object.
You're also making it difficult on yourself when trying to determine the animal. Use Array.findIndex() if your browser supports it.
Here's a working example:
var obj = {animals:[{CommonName:"Royal Python",Order:"Squamata",Family:"Boidae",Genus:"Python",Species:"regius",Zoo:"Blackpool Zoo",Number:4 }, {CommonName:"Emperor Penguin",Order:"Sphenisciformes",Family:"Spheniscidae",Genus:"Aptenodytes",Species:"forsteri",Zoo:"Welsh Mountain Zoo",Number:35 }, {CommonName:"Chimpanzee",Order:"Primates",Family:"Pongidae",Genus:"Pan",Species:"troglodytes", Zoo:"Blackpool Zoo",Number:8 }]};
//function to fetch data based on input
function myFunction() {
var name = document.getElementsByName("fname")[0].value;
var index = obj.animals.findIndex(function(item) {
return item.CommonName === name;
});
if (index >= 0) {
document.getElementById("demo").innerHTML = obj.animals[index].Zoo + " " + obj.animals[index].Species;
}
}
<input type="text" name="fname" required value="Royal Python">
<button onclick="myFunction()">OK</button>
<p id="demo"></p>
trying to use appendChild to create a child element in a paragraph, I think I'm missing something fundamental here but I can't figure out what and not sure I'm using appendChild correctly.
<!DOCTYPE html>
<html>
<body>
<p>Accessing Variables from an Array</p>
<p id="demo"></p>
<script>
var employees = [
{
"firstName":"John",
"lastName":"Doe"
},
{
"firstName":"Anna",
"lastName":"Smith"
},
{
"firstName":"Peter",
"lastName":"Jones"
}
];
document.getElementById("demo").innerHTML =
employees[0].firstName + " " + employees[0].lastName;
childtest=document.getElementById("demo").innerHTML=employees[1].firstName;
first = document.getElementById("demo");
first.appendChild(childtest);
</script>
</body>
</html>
What I'm trying to do is create a child of "demo" and take the second array of employees and make that the child element and output that underneath the first output.
childtest is not a element here.
// Create a new empty <p> element.
var childtest = document.createElement('p');
// Set the innerHTML.
childtest.innerHTML = employees[1].firstname;
// Append that <p> element.
first.appendChild(childtest);
your problem is that you're not creating a new element and with .innerHTML you're just overwriting existing
fiddle
var employees = [{
"firstName": "John",
"lastName": "Doe"
}, {
"firstName": "Anna",
"lastName": "Smith"
}, {
"firstName": "Peter",
"lastName": "Jones"
}];
document.getElementById("demo").innerHTML = employees[0].firstName + " " + employees[0].lastName;
var newEl = document.createTextNode(employees[1].firstName);
first = document.getElementById("demo");
first.appendChild(newEl);
Katpoes got it right, just for clarification, this works:
<!DOCTYPE html>
<html>
<body>
<p>How to create a JavaScript object array.</p>
<p id="demo"></p>
<script>
var employees = [
{
"firstName":"John",
"lastName":"Doe"
},
{
"firstName":"Anna",
"lastName":"Smith"
},
{
"firstName":"Peter",
"lastName":"Jones"
}
];
document.getElementById("demo").innerHTML =
employees[0].firstName + " " + employees[0].lastName;
var childtest=document.createElement("p");
childtest.innerHTML = employees[1].firstName;
first = document.getElementById("demo");
first.appendChild(childtest);
</script>
</body>
</html>
function myFunction()
{
var x;
var txt="";
var person={fname:"John",lname:"Doe",age:25};
for (x in person)
{
txt=txt + person[x];
}
document.getElementById("demo").innerHTML=txt;
}
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
This function should display one property of the object person every time the button is clicked (first "John", then "Doe", and finally 25). However, the first time the button is clicked, the output is JohnDoe25. How can this function be modified so that it fits the requirement?
It's better to use array but in your case,
Yo can do it like this: LIVE DEMO
<script>
var x = 0;
var txt="";
var person={fname:"John",lname:"Doe","age":25};
function myFunction(){
if(x==0){
txt = person['fname'];
}
if(x==1){
txt = person['lname'];
}
if(x==2){
txt = person['age'];
}
x++;
document.getElementById("demo").innerHTML = txt;
}
</script>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>