GET item from brackets in array javascript - javascript

I need some help. Here I have a string.
n[0] = '3(10)';
The task is to get only 10 from brackets. How to do it in javascript?

You can solve this with Regex :
This will do :
var a= '3(10)'.match(/\((.*?)\)/)
alert(a[1]) ;//10
The captured group will appear in the second index of the array (1)
Regarding your other comment/question :
I have a[0] = '3(10,5) 7(9,4)'; 10 and 9 are chances the task is to
get the number (3 or 7) with a bigger chance (10)
var finalNumber=-1;
var finalChance=-1;
var a = '3(10,5) 7(9,4)';
var m=a.match(/(\d+?)\((\d+?)\,/g);
for (var i=0;i<m.length;i++)
{
var number=m[i].match(/(\d+)\(/)[1]
var chance=m[i].match(/\((\d+)\,/)[1]
if (+chance>+finalChance)
{
finalChance=chance;
finalNumber=number;
}
}
console.log(finalNumber)
Jsbin

Use split() function to split your string with brackets two times :
var first_split = n[0].split(')')[0]; //first_split will return "3(10"
var result = first_split.split('(')[1]; //second split will return "10";
//To reduce the code you can do it in 1 line like this
var result = n[0].split(')')[0].split('(')[1]; // result = "10"

Related

How can I display an array in HTML so that numbers are broken into new line

I am trying to display an array in HTML so that the displayed integers are broken into a new line. The JS is breaking them into a new line, yes, but when the numbers are single number like from 0 - 9, they don't break into a new line. The numbers that break into a new line only start from double digit ie. 10 going upwards.
Here is my JS code: I think there is something wrong with the FOR LOOP in the function displayArray, but I just cant figure it out. This is one of the final pieces to almost tie this up!
Thanking you in advance for any contributions!
//Array to hold statistics of number of pages read per sitting over a period of time
const myArray = [];
//Function to calculate number of pages read
let calculate = () => {
var start = document.getElementById("number1").value;
var end = document.getElementById("number2").value;
document.getElementById("number1").value = ""; // make START empty
document.getElementById("number2").value = ""; //make END empty
let totalNumber = end - start;
myArray.push(totalNumber); //Push total number into array
document.getElementById("congrats").textContent =
"Congrats, you read " + totalNumber + " pages today!";//display message
document.getElementById("rightpane").textContent = myArray;//push array into HTML
displayArray();//Call display array
};
//Function to display myARRAY broken down to a new line
const displayArray = ()=> {
let displayedNumbers='';
for (i = 0; i < myArray.length; i++){
displayedNumbers += myArray[i] + "\n";
};
document.getElementById("rightpane").textContent = displayedNumbers;//Append myArray into HTML
}
Append a prefixed 0 to any number less than 10
You could append a number to the start of the list item and increase it by one each time.
I'm not really sure what you are trying to do, but if you want numbers to appear in new line without using lists and CSS you can wrap them in 'pre' tags and it should break it to new row like this:
displayArray();
function displayArray(){
myArray = [0,1,2,3,4];
let displayedNumbers='';
for (i = 0; i < myArray.length; i++){
displayedNumbers += "<pre>"+myArray[i] + "</pre>";
};
document.getElementById("rightpane").innerHTML = displayedNumbers;//Append myArray into HTML
}
#rightpane{
background : #000;
height : 200px;
width: 100px;
color:white;
padding: 5px;
}
<pre>0</pre><pre>1</pre><pre>2</pre><pre>3</pre>
<div id="rightpane"></div>
I have just made your code some corrections...
and adding parseInt
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
and you also have to look at white-space: pre
https://developer.mozilla.org/en-US/docs/Web/CSS/white-space
// Array to hold statistics of number of pages read per sitting over a period of time
const myArray = []
, Num_1 = document.getElementById('number1')
, Num_2 = document.getElementById('number2')
, congrats = document.getElementById("congrats")
, rightpane = document.getElementById("rightpane")
const LeadZeros =(val,lg)=>('0'.repeat(lg)+val).slice(-lg)
// Function to calculate number of pages read
const calculate =_=>
{
let totalNumber = parseInt(Num_2.value) - parseInt(Num_1.value)
Num_1.value = '' // make START empty
Num_2.value = '' // make END empty
myArray.push( LeadZeros(totalNumber,3) ) // Push total number into array
/*
// or:
myArray.push( totalNumber.toString(10).padStart(3, '0') )
*/
congrats.textContent = `Congrats, you read ${totalNumber} pages today!` // display message
rightpane.textContent = myArray.join("\n") // push array into HTML
}
I also remove your function DisplayArray() and use Array.join() method .
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join
leadZero function use :
https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/String/repeat
https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/String/slice
leadZero is divided into two parts: (for example lg = 3)
1) '0'.repeat (3) + val ===' 000 '+ val
if val = 5 it gives '0005'
if val = 42 this gives '00042'
nota: the first value is a string and force the setting in value string too
2) () .slice (-lg) <=> () .slice (-3)
when we put a negative value the method string.slice pars the last character and goes up (from 3 here)
the last 3 characters of:
'0005'.slice(-3) => '005'
'00042'.slice(-3) => '042'

how to get varaiable if only have more than 3 letters javascript

var result="stackoverflow";
var string="22342st";
if(more than 3 letters)
{
var new=data;
}
1)how I can get variable if only have more than
using match() (function ) in javascript
2)what if I do getting variable in for time delay
some (because of TCP connection)
Does anyone have an idea?
you can use .length property to check string length is greater than 3 or not.
var result = "stackoverflow";
if(result.length > 3)
{
//Your business logic goes here
}
if you want to check only character counts in string is greater than three then you can try below code
var input = "45749ce";
var result = input.match(/[a-zA-Z]/gi);
if(result.length > 3)
{
//Your business logic goes here
console.log(`${result} length is greater than 3`);
}
That should work
var myRegEx = /[a-zA-Z(.+)]{3}/g;
var myString="22342st";
if(myString.match(myRegEx)!==null)
{
}
Also
myString.match(myRegEx)
will return an array of matched values, so you can work with them if needed.
To find the more than three letter in variable using match you have to need regex
([a-zA-Z0-9)]){3,}
code how looks like
var result="stackoverflow";
var string="22342st";
var res = string.match(/([a-zA-Z0-9)]){3,}/g);
if(res!=null){
//here what you want
}

Input field values not arithmetically summing up

Goodday, please i have a code to calculate the efficiency of a generator. The problem is the input fields all add up until the last variable. If all values were 2+2+3+4 which normally sums up into 11 normally, this program doesn't do that instead it just adds the 4 as in 2+2+3+4 equals 74.
That's the formula for calculating the efficiency of a generator.
$('.efmit').on('click', function efficiency() {
var vI = $('.I').val();
var vV = $('.V').val();
var ia = $('.ia').val();
var If = $('.If').val();
var Ra = $('.Ra').val();
var closs = $('.closs').val();
var vi_combo = vI*vV;
var ias = (ia*ia)*Ra;
var iv = If*vV;
var cent = 100;
var result = vi_combo+ias + iv;
var finalR = result + closs;
window.alert(finalR);
})
jQuery val method like $('.closs').val() returns String type variable not Number type.
You can cast type of variable to solve the problem.
var closs = Number($('.closs').val());
The reason is your program treated your variable as a string
try converting them to integer by parsing them like this parseInt(yourVariable).

get value of string before and after / in javascript

suppose i have 10 localstorage like blow:
localStorage.setItem("item01","this is a value/100");
localStorage.setItem("item02","this new is a value/110");
localStorage.setItem("item03","this is a good value/120");
localStorage.setItem("item04","this is a nice value/130");
I need a java script code to check if the key of for example item01 is not 0 then put the data of item01 before / to xyz and the data after / to rfv variable.
I would suppose you split the data-string along the character "/". Something like:
var lsData = localStorage.getItem("item01");
var dataArray = lsData.split("/");
if(dataArray.length === 2){
var xyz = dataArray[0];
var rfv = dataArray[1];
}
else{
... error-code (could not split exactly)...
}
This is an answer to your question "get value of string before and after / in javascript".
Like I stated in the comments you can split a string into an array of substrings using a delimiter.
jsfiddle
var str= "this is a value/100";
var temp=str.split("/");
var xyz = temp[0]; //->this is a value
var rfv = temp[1]; //->100
alert('xyz = '+xyz+'\nrfv = '+rfv);
this should do it...
I'm assuming you know how to get the localStorage value, so I'm just posting an example.
var a = "this is a value/100"
var b = /^(.*?)\/(\w+)/.exec(a);
var text = b[1]
var value = b[2]

How can I "count characters" in a regex?

I'm not sure if count is the right word to use because it doesn't really matter to me how many there are, but let me explain. My data will be formatted like this: (hi,(1,2),hey),(yo,(3,(rawr),4),howdy) and I have no control over how many dimensions there are. And I want to grab the lowest groups ["hi", Array[], "hey"] and ["yo", Array[], "howdy"] So if there was a way to "count" I could count the open parenthesis, and then count the closed ones and when it hits 0, that's when the regex ends. For example:
(hi,(1,2),hey),(yo,(3,(rawr),4),howdy)
1---2---1----0-1---2--3----2--1------0
Now with that being said, I don't believe counting is possible but what I want is a subsitute solution. This is what I have so far /\([^\(]*?\)/ but that only returns the highest level group from each of the low-level groups aka (1,2) and (rawr).
You can use a stack to track the (and).
Array.reduce(
'(hi,(1,2),hey),(yo,(3,(rawr),4),howdy)',
function(x,y){
if(y=='(')
return [x[0]+1, x[1]+(x[0]+1)]
else if(y==')')
return [x[0]-1, x[1]+(x[0]-1)]
else
return [x[0], x[1]+'-']
},
[0,'']
)[1]
Try it in firebug console.
This works for the original use-case and #Barmar's use-case - and it counts the parenthesis, if you really wanted that...
Also, I added arbitrary spaces all over the data strings - just in case (since you have no control over the incoming data)
var results = [];
var dataString = "(hi, (1,2) , hey), ( yo,( 3, ( rawr ), 4) , howdy )";
//var dataString = "(hi, (1 , 2 ), (3, 4), hey), (yo ,(3,(rawr ), 4), howdy)";
var dataSplit = dataString.split(",");
var trimRegex = /^\s+|\s+$/g;
var openParensRegex = /\(/;
var closeParensRegex = /\)/;
var parensRegex = /\(|\)/;
var parensCount = 0;
for (var x = 0, lenx = dataSplit.length; x < lenx; x++){
var cleanString = dataSplit[x].replace(trimRegex, "");
if (openParensRegex.test(cleanString)){ parensCount++; };
if (parensCount < 2){
results.push(cleanString.replace(parensRegex, "").replace(trimRegex, ""));
};
if (closeParensRegex.test(cleanString)){ parensCount--; };
};
console.log(results);
Hope that helps!
The following script might help, it will identify the parenthesis levels:
var string="(hi,(1,2),hey),(yo,(3,(rawr),4),howdy)",i=0;
while (string.indexOf("(")>=0) {
i++;
string=string.replace(/\(([^()]+)\)/g,"|l"+i+"|$1|l"+i+"|");
}
Result:
|l2|hi,|l1|1,2|l1|,hey|l2|,|l3|yo,|l2|3,|l1|rawr|l1|,4|l2|,howdy|l3|
Fiddle: http://jsfiddle.net/GfUZh/
If you want to get the highest levels you can probably do it with regex by finding the intersection points, in this case ),(.
var str = '(hi,(1,2),hey),(yo,(3,(rawr),4),howdy)';
var re = /(\(.+\)),(\(.+\))/;
var results = re.exec(str);
results.shift(); // remove first item which is useless
console.log(results); //=> ["(hi,(1,2),hey)", "(yo,(3,(rawr),4),howdy)"]
Demo: http://jsfiddle.net/elclanrs/fFmfE/

Categories