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

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//

Related

Javascript Array is displayed with unwanted comma

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.

How do I correctly apply regex so array does not have empty string at the start

I'm struggling with a regex.
I am able to split the string at the required location, but when it is added to an array, the array has an empty string at the start.
// This is the string I am wanting to split.
// I want the first 4 words to be separated from the remainder of the string
const chatMessage = "This is a string that I want to split";
// I am using this regex
const r = /(^(?:\S+\s+\n?){4})/;
const chatMessageArr = chatMessage.split(r);
console.log(chatMessageArr);
It returns:
[ '', 'This is a string ', 'that I want to split' ]
But need it to return:
[ 'This is a string ', 'that I want to split' ]
I wouldn't use string split here, I would use a regex replacement:
var chatMessage = "This is a string that I want to split";
var first = chatMessage.replace(/^\s*(\S+(?:\s+\S+){3}).*$/, "$1");
var last = chatMessage.replace(/^\s*\S+(?:\s+\S+){3}\s+(.*$)/, "$1");
console.log(chatMessage);
console.log(first);
console.log(last);
Add a second capture group to the regexp and use .match() instead of .split().
// This is the string I am wanting to split.
// I want the first 4 words to be separated from the remainder of the string
const chatMessage = "This is a string that I want to split";
// I am using this regex
const r = /(^(?:\S+\s+\n?){4})(.*)/;
const chatMessageArr = chatMessage.match(r);
chatMessageArr.shift(); // remove the full match
console.log(chatMessageArr);

Why [,,].join(' ') length is one less than array length?

What is the reason behind the length of string produced by joining var arr = [,,], like so: var str = arr.join(' ') being one less than length of arr.
var literal_arr = [,,],
joined_literal_arr = literal_arr.join(' '),
constructor_arr = new Array(2),
joined_constructor_arr = new Array(2).join(' ');
console.log("Literal array notation length = ", literal_arr.length);
console.log("Joined literal array notation string length = ", joined_literal_arr.length);
console.log("Constructor array notation length = ", constructor_arr.length);
console.log("Joined constructor notation string length = ", joined_constructor_arr.length);
As per MDN docs :
If an element is undefined or null, it is converted to the empty string.
In your case, you are creating an array with a particular length without any value(it would be undefined). So while joining there will be length - 1 separators(since undefined already treated as an empty string) means length - 1 spaces(' ').
It is simple as .join will join array elements with separator provided as argument. It won’t append separator after the last element or prepend it before the first element. It will place separator between elements only.

Why is this regex matching also words within a non-capturing group?

I have this string (notice the multi-line syntax):
var str = ` Number One: Get this
Number Two: And this`;
And I want a regex that returns (with match):
[str, 'Get this', 'And this']
So I tried str.match(/Number (?:One|Two): (.*)/g);, but that's returning:
["Number One: Get this", "Number Two: And this"]
There can be any whitespace/line-breaks before any "Number" word.
Why doesn't it return only what is inside of the capturing group? Am I misundersating something? And how can I achieve the desired result?
Per the MDN documentation for String.match:
If the regular expression includes the g flag, the method returns an Array containing all matched substrings rather than match objects. Captured groups are not returned. If there were no matches, the method returns null.
(emphasis mine).
So, what you want is not possible.
The same page adds:
if you want to obtain capture groups and the global flag is set, you need to use RegExp.exec() instead.
so if you're willing to give on using match, you can write your own function that repeatedly applies the regex, gets the captured substrings, and builds an array.
Or, for your specific case, you could write something like this:
var these = str.split(/(?:^|\n)\s*Number (?:One|Two): /);
these[0] = str;
Replace and store the result in a new string, like this:
var str = ` Number One: Get this
Number Two: And this`;
var output = str.replace(/Number (?:One|Two): (.*)/g, "$1");
console.log(output);
which outputs:
Get this
And this
If you want the match array like you requested, you can try this:
var getMatch = function(string, split, regex) {
var match = string.replace(regex, "$1" + split);
match = match.split(split);
match = match.reverse();
match.push(string);
match = match.reverse();
match.pop();
return match;
}
var str = ` Number One: Get this
Number Two: And this`;
var regex = /Number (?:One|Two): (.*)/g;
var match = getMatch(str, "#!SPLIT!#", regex);
console.log(match);
which displays the array as desired:
[ ' Number One: Get this\n Number Two: And this',
' Get this',
'\n And this' ]
Where split (here #!SPLIT!#) should be a unique string to split the matches. Note that this only works for single groups. For multi groups add a variable indicating the number of groups and add a for loop constructing "$1 $2 $3 $4 ..." + split.
Try
var str = " Number One: Get this\
Number Two: And this";
// `/\w+\s+\w+(?=\s|$)/g` match one or more alphanumeric characters ,
// followed by one or more space characters ,
// followed by one or more alphanumeric characters ,
// if following space or end of input , set `g` flag
// return `res` array `["Get this", "And this"]`
var res = str.match(/\w+\s+\w+(?=\s|$)/g);
document.write(JSON.stringify(res));

JS: determine amount of occurrences in a string

Is there a way to determine the number of times a letter occurs inside another string?
if not, can you determine the number of times a string is in an array
if you can do it with the array, how can you split 2 words, such as: Hello, World! into an array of 2 words, like this:
["Hello", "World"]
Sure. A simple one liner that comes to mind is
var numOccurrences = str.split("<char>").length -1
where can be replaced with whatever character (or string) you want to test for
That will split the string on each occurrence and then take the length of the resulting array -1. Which will tell you the number of occurrences.
If you want to do it while ignoring upper/lower case, you can use regex
str.match(/<char>/gi).length
The number of times a letter occurs in a string
This can be found as follows:
"Hello World Hello World!".match(/e/g).length // Will result in 2
/e/g is a regular expression that matches the letter 'e'. The 'g' stands for "global" and gets all the occurances in a string.
String in an array
This can be found as follows:
var arrayOfStrings = ["Hello", "World", "Hello", "World"],
wordCount = 0,
i;
for (i = 0; i < arrayOfStrings.length; i += 1) { // Remember to optimise length call
if (arrayOfStrings[i] === "Hello") {
wordCount += 1;
}
}
console.log(wordCount) // This will log 2

Categories

Resources