Javascript Array is displayed with unwanted comma - javascript

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.

Related

How Can I show the second array from string came from .split()

I have this string
a = "This is just an example";
If I used
split(" ",1)
it will print the first word as an array.
My question is how can I split just the second string as an array?
Use a limit of 2, then slice starting from the second element.
a = "This is just an example";
console.log(a.split(" ", 2).slice(1));
Or split the string with a limit of 2, then use an array literal containing just the second element.
a = "This is just an example";
console.log([a.split(" ", 2)[1]]);
A Better Approach would be to split on a space & that will give you an array of string, select the index you want & split it further
Note : ARRAY INDEX STARTS FROM 0 NOT ONE, SO IF YOU WANT THE SECOND STRING, YOU WILL HAVE TO USE THE INDEX 1, NOT 2
const a = "This is just an example";
const secondWordArr = a.split(' ')[1].split('');
// secondWordArr represents the array of characters of the seconds word
console.log(secondWordArr); // Output [ 'i', 's' ]
Explanation :
a.split(' ') // this splits the string into an array of strings/words
a.split(' ')[1] // Access the second string in the array of split strings/words
a.split(' ')[1].split('') // splits the second string from the array of strings/words into a separate array//

Javascript - map(function) return this.value - comma on wrong side

I use this code for listing all checked values in the array:
var healthSafety = $('input:checkbox[name=health_safety]:checked').map(function() {
return this.value + (' ');
}).get();
but the problem is, that comma, which separates them falls in the wrong place.
I get something like:
Tripple ladders ,Skylight ,Access to roof
but I want something like this:
Tripple ladders, Skylight, Access to roof.
I tried to put:
return this.value + (' ');
but it didn't helped
Is any way to fix it?
You're relying on implicit join, which puts a comma after each item, but your items (once you update them) end with a space.
Do an explicit join instead with the separator you want:
var healthSafety = $('input:checkbox[name=health_safety]:checked')
.map(function() { return this.value; })
.get()
.join(", ");
or perhaps
const healthSafety = $('input:checkbox[name=health_safety]:checked')
.get()
.map(({value}) => value)
.join(", ");
In your question, you are viewing the default serialization of your array, which only uses a single-character , as a separator. You're trying to add spaces to the separation by adding them to the values.
But you don't want the values to include spaces: that will result in an extra space either at the beginning or ending of the string. Instead, you want to serialize the array with the two-character separator , (comma + space). You can perform this serialization with join:
$('...').map(function() {
return this.value;
}).get().join(", ");
You didn't post the offending code, but somewhere you're stringifying an array, which automatically concatenates all of the elements with a comma:
console.log(['a', 'b', 'c']); //-> "a,b,c"
In your case, you're adding a space to the end of each value, so you're ending up with something like this:
console.log(['value1 ', 'value2 ', 'value3 ']); //-> "value1 ,value2 ,value3 "
What you want to do is remove the extra space as you currently have it and then call .join(', ') on the array - notice the extra space after the comma:
console.log(['value1', 'value2', 'value3'].join(', ')); //-> "value1, value2, value3"
You can join the array with any string:
console.log(['value1', 'value2', 'value3'].join('.:::.')); //-> "value1.:::.value2.:::.value3"

NODEJS: extracting strings between two DIFFERENT characters and storing them in an array

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

JavaScript split gives array size one instead of zero for empty string

I want to split a string by comma to get an array in Node.js.
exports.test = function(rq, rs){
var mailList = "sharan#test.com,pradeep#test.com";
var arrayList = mailList.split(",");
console.log(mailList + " array lenght " + arrayList.length );
mailList = "";
arrayList = mailList.split(",");
console.log(mailList + " array lenght " + arrayList.length );
mailList = "sharan#test.com,";
console.log(mailList + " array lenght " + arrayList.length );
mailList = ",";
console.log(mailList + " array lenght " + arrayList.length );
rs.send("test here ");
}
The console output is:
sharan#test.com,pradeep#test.com array lenght 2
array lenght 1
sharan#test.com, array lenght 1
, array lenght 1
Why does the JavaScript "".split() return an array with one element instead of an empty array?
The returned array contains a single empty string ([""]). It works this way because everything up until the first match (or end of string) is returned as the first element of the array. In the case of the empty string, this is an empty string.
If you think about how an implementation of the split algorithm might look like, this makes sense. Probably you start with an empty string containing the current element, and then you loop through the letters of the string adding them to the current element until you get to the end of the string or a separator. Then you push the current element onto the results array.
In the case where you have a zero length string, you start with an empty string for the current element. You directly reach the end, so you push the empty string to the results array an return it.
This is also how it is supposed to work. From the ECMAScript Language Specification:
If the this object is (or converts to) the empty String, the result depends on whether separator can match the empty String. If it can, the result array contains no elements. Otherwise, the result array contains one element, which is the empty String.
And from Mozilla:
When found, separator is removed from the string and the substrings are returned in an array. If separator is not found or is omitted, the array contains one element consisting of the entire string.
Note: When the string is empty, split() returns an array containing one empty string, rather than an empty array.
If you dislike the behavior, you can write your own version:
//Return an empty array if string is empty.
//Otherwise return the result of the ordinary split.
split2 = (separator) => this == "" ? [] : this.split(separator);
Everything before the first match is returned as the first element. Even if the String is Empty. It's not null
If you want split and return an 0 length Array, I recommand you to use the underscore.string module and the words method :
_str.words("", ",");
// => []
_str.words("Foo", ",");
// => [ 'Foo' ]
One way to do is to check whether the first value of the split array is empty or not
var arrayList = mailList.split(",");
if(arrayList[0] != ""){
arrayLength = arrayList.length;
}else{
arrayLength = 0;
}

Separate value from string using javascript

I have a string in which every value is between [] and it has a . at the end. How can I separate all values from the string?
This is the example string:
[value01][value02 ][value03 ]. [value04 ]
//want something like this
v1 = value01;
v2 = value02;
v3 = value03;
v4 = value04
The number of values is not constant. How can I get all values separately from this string?
Use regular expressions to specify multiple separators. Please check the following posts:
How do I split a string with multiple separators in javascript?
Split a string based on multiple delimiters
var str = "[value01][value02 ][value03 ]. [value04 ]"
var arr = str.split(/[\[\]\.\s]+/);
arr.shift(); arr.pop(); //discard the first and last "" elements
console.log( arr ); //output: ["value01", "value02", "value03", "value04"]
JS FIDDLE DEMO
How This Works
.split(/[\[\]\.\s]+/) splits the string at points where it finds one or more of the following characters: [] .. Now, since these characters are also found at the beginning and end of the string, .shift() discards the first element, and .pop() discards the last element, both of which are empty strings. However, your may want to use .filter() and your can replace lines 2 and 3 with:
var arr = str.split(/[\[\]\.\s]+/).filter(function(elem) { return elem.length > 0; });
Now you can use jQuery/JS to iterate through the values:
$.each( arr, function(i,v) {
console.log( v ); // outputs the i'th value;
});
And arr.length will give you the number of elements you have.
If you want to get the characters between "[" and "]" and the data is regular and always has the pattern:
'[chars][chars]...[chars]'
then you can get the chars using match to get sequences of characters that aren't "[" or "]":
var values = '[value01][value02 ][value03 ][value04 ]'.match(/[^\[\]]+/g)
which returns an array, so values is:
["value01", "value02 ", "value03 ", "value04 "]
Match is very widely supported, so no cross browser issues.
Here's a fiddle: http://jsfiddle.net/5xVLQ/
Regex patern: /(\w)+/ig
Matches all words using \w (alphanumeric combos). Whitespace, brackets, dots, square brackets are all non-matching, so they don't get returned.
What I do is create a object to hold results in key/value pairs such as v1:'value01'. You can iterate through this object, or you can access the values directly using objRes.v1
var str = '[value01][value02 ][value03 ]. [value04 ]';
var myRe = /(\w)+/ig;
var res;
var objRes = {};
var i=1;
while ( ( res = myRe.exec(str) ) != null )
{
objRes['v'+i] = res[0];
i++;
}
console.log(objRes);

Categories

Resources