I have this following pug array and let it execute in an each. The problem is the values are listed with commas. I want it without commas.
I could write the array in the each like each x, y in {'value1': 'value2', ...} but that isnt comfortable.
The current code:
-
var starWars = {
"people": [
"Yoda",
"Obi-Wan",
"Anakin"
],
"rank": [
"master",
"master",
"knight"
]
}
each person, rank in {starWars}
p= person.people
p= person.rank
Output:
Yoda,Obi-Wan,Anakin
master,master,knight
The = character after the tag p is for buffered code. Any JavaScript expression is valid input and will be converted to a string before being printed.
So when you put in an array, it is converted to the string representation of that array which is to separate each element with a comma.
Add a .join(" ") after each array to convert them to a string yourself and delimit them by space rather than comma:
each person, rank in {starWars}
p= person.people.join(" ")
p= person.rank.join(" ")
Output with my changes:
Yoda Obi-Wan Anakin
master master knight
Related
I need your help:
In Javascript I create an array with push.
for (const elem of prod[i].motor) {
if (usedMotor.includes(elem) === false) {
motor.push('<li>'+elem+'</li>');
usedMotor.push(elem);
}
}
But if I want to display it with document.getElementById('spanMotorType').innerHTML = 'Applicable Motors:'+ motor;
it is printed with comma between the elements.
Applicable Motors:
Induction motor
,
Permanent magnet motor
,
Synchronous reluctance motor
Console shows this:
Array(3) [ "<li>Induction motor</li>", "<li>Permanent magnet motor</li>",
"<li>Synchronous reluctance motor</li>" ]
0: "<li>Induction motor</li>"
1: "<li>Permanent magnet motor</li>"
2: "<li>Synchronous reluctance motor</li>"
Is there a way how I can remove this comma? The length of the Array can be between 1 and 3.
thanks
Write it as follows:
document.getElementById('spanMotorType').innerHTML = 'Applicable Motors:'+ motor.join(' ');
Explanation:
By default, when a string is joined with an Array, the output will print the array items with a comma, because it converts it, as-is, to string, and since there's a comma between Array items, it will also be printed:
document.write( "foo " + ['a','b','c'] )
Without commas:
document.write( "foo " + ['a','b','c'].join(' ') )
Array join converts an Array to a string with your choice of delimiter and not the default comma.
Use following code.
usermotor.join(" ")
https://sebhastian.com/javascript-array-string/
Setting Array as the innerHTML will bind the element with comma. Because Array inclueds that comma when its converted to string.
You have to make the array as a single sting and set the innerHTML to get rid of the comma.
Joing the array using Array.join, I used empty sting as the joiner. Set the innerHTML with this joined string.
const testArr = [1, 2, 3];
const myarray = testArr.map((node) => '<li>' + node + '</li>')
document.getElementById("test").innerHTML = myarray.join('');
<div id="test"></div>
So in your case it should be
document.getElementById('spanMotorType').innerHTML = 'Applicable Motors:'+ motor.join('');
Please Note
You have to mention some string with which the array is to be joined, or else , will be treated as default joiner.
I have been trying to wrap some malformed JSON values with double quotes. The response is from a Java Servlet (its actually a hashmap) which I have no control over. I have managed to get it from this:
{ response={ type=000, products=[{id=1,name=productone},{id=2,name=producttwo}],status=success}}
to this:
{"response": { "type": 000, "products": [{"id": 1,"name": productone},{"id": 2,"name": producttwo}],"status": success}}
using the following regexes:
hashmap = hashmap
.replace (/ /g,"").replace(/\s/g,"") //replace all spaces
.replace (/'/g,"").replace(/"/g,'') //replace all quotes
.replace(/=/g,":") //replace = with :
.replace(/(['"])?([a-z0-9A-Z_]+)(['"])?:/g, '"$2": '); //put quotes around keys
How would I go around wrapping the values with double quotes using a regex. Any help is highly appreciated.
EDIT :
I would eventually want it to be in this form :
{"response": { "type": "000", "products": [{"id": "1","name": "productone"},{"id": "2","name": "producttwo"}],"status": "success"}}
Here's a way to quote all keys and values, as you want:
hashmap = hashmap.replace(/ /g, '') // strip all spaces
.replace(/([\w]+)=/g, '"$1"=') // quote keys
.replace(/=([\w]+)/g, ':"$1"') // quote values
.replace(/=([[{])/g, ':$1'); // = to : before arrays and objects also
This produces:
{"response":{"type":"000","products":[{"id":"1","name":"productone"},{"id":"2","name":"producttwo"}],"status":"success"}}
Now you can convert it to JavaScript object with:
obj = JSON.parse(hashmap);
However, more in line with JSON parsing would be not to quote numeric values, but rather to parse them as numbers, like this:
hashmap = hashmap.replace(/ /g, '')
.replace(/([\w]+)=/g, '"$1"=')
.replace(/=([a-zA-Z_]+)/g, ':"$1"')
.replace(/=([\d]+)/g, function(m, num) {return ':'+parseFloat(num)})
.replace(/=([[{])/g, ':$1')
This produces:
{"response":{"type":0,"products":[{"id":1,"name":"productone"},{"id":2,"name":"producttwo"}],"status":"success"}}
Using nodejs, I need to extract ALL strings between two characters that are DIFFERENT, and store them in an array for future use.
For instance, consider a file, containing a file with the following content.
"type":"multi",
"folders": [
"cities/",
"users/"
]
I need to extract the words: cities and users, and place them in an array. In general, I want the words between " and /"
As Bergi mentions in a comment, this looks suspiciously similar to JSON (javascript object notation.) So I'll write my answer assuming that it is. For your current example to be valid JSON, it needs to be inside object-brackets like this:
{
"type": "multi",
"folders": [
"cities/",
"users/"
]
}
If you parse this:
var parsed_json = JSON.parse( json_string );
// You could add the brackets yourself if they are missing:
var parsed_json = JSON.parse('{' + json_string + '}');
Then all you have to do to get to the array:
var arr = parsed_json.folders;
console.log(arr);
And to fix the annoying trailing slashes we remap the array:
// .map calls a function for every item in an array
// And whatever you choose to return becomes the new array
arr = arr.map(function(item){
// substr returns a part of a string. Here from start (0) to end minus one (the slash).
return item.substr( 0, item.length - 1 );
// Another option could be to instead just replace all the slashes:
return item.replace( '/' , '' );
}
Now the trailing slashes are gone:
console.log( arr );
This should work.
"(.+?)\/"
" preceding
1 or more character (non-greedy)
followed by /"
REGEX101
I want to split a string into an array using "space and the comma" (" ,") as the separator. Through looking through some similar questions I figured out how to make them work as one separator. However I want them to work ONLY as one. So I do not want the array to be separated by only comma's or only spaces.
So I'd like the string "txt1, txt2,txt3 txt4, t x t 5" become the array txt1, "txt2,txt3 txt4", "t x t 5"
Here is my current code which doesn't do this:
var array = string.split(/(?:,| )+/)
Here is a link to the jsFiddle: http://jsfiddle.net/MSQxk/
Just do: var array = string.split(", ");
You can use this
var array = string.split(/,\s*/);
//=> ["txt1", "txt2", "txt3", "txt4", "t x t 5"]
This will compensate for strings like
// comma separated
foo,bar
// comma and optional space
foo,bar, hello
If you wanted to compensate for optional whitespace on each side of the comma, you could use this:
// "foo,bar, hello , world".split(/\s*,\s*);
// => ['foo', 'bar', 'hello', 'world']
Here's what I need in what I guess must be the right order:
The contents of each section of the string contained in square brackets (which each must follow after the rest of the original string) need to be extracted out and stored, and the original string returned without them.
If there is a recognized string followed by a colon at the start of a given extracted section, then I need that identified and removed.
For what's left (comma delimited), I need it dumped into an array.
Do not attempt to parse nested brackets.
What is a good way to do this?
Edit: Here's an example of a string:
hi, i'm a string [this: is, how] [it: works, but, there] [might be bracket, parts, without, colons ] [[nested sections should be ignored?]]
Edit: Here's what might be the results:
After extraction: 'hi, i'm a string'
Array identified as 'this': ['is', 'how']
Array identified as 'it': ['works', 'but', 'there']
Array identified without a label: ['might by bracket', 'parts', 'without', 'colons']
Array identified without a label: []
var results = [];
s = s.replace(/\[+(?:(\w+):)?(.*?)\]+/g,
function(g0, g1, g2){
results.push([g1, g2.split(',')]);
return "";
});
Gives the results:
>> results =
[["this", [" is", " how"]],
["it", [" works", " but", " there"]],
["", ["might be bracket", " parts", " without", " colons "]],
["", ["nested sections should be ignored?"]]
]
>> s = "hi, i'm a string "
Note it leaves spaces between tokens. Also, you can remove [[]] tokens in an earlier stage by calling s = s.replace(/\[\[.*?\]\]/g, ''); - this code captures them as a normal group.