How to extract multiple integers from a single array item - javascript

Would somebody here please show me the way to modify the regexp below so that I could then with it get multiple integers per array item? I can detect one integer like in the top-most str below using \d+. However, the function will error out with the other two examples, below it, str = "7yes9 Sir2", etc. Thank you.
//str = "10 2One Number*1*";
//output -> [10, 2One, Number*1*] -> [10 + 2 + 1] -> 13
var str = "7Yes9 Sir2";
//output -> NaN
//var str = "8pop2 1";
//output -> NaN
function NumberAddition(str) {
input = str.split(" ");
var finalAddUp = 0;
var finalArr = [];
for(var i = 0; i<=input.length-1; i++) {
var currentItem = input[i];
var regexp = /(\d+)/g;
finalArr.push(Number(currentItem.match(regexp)));
var itemToBeCounted = +finalArr[i];
finalAddUp += itemToBeCounted;
}
return finalAddUp;
}
console.log(NumberAddition(str));

Try sth. like
HTML
<span id="res"></span>
JS
var str = "7Yes9 Sir2";
var matches = str.match(/\d+/g);
var res=0;
for (var i=0; i< matches.length; i++) {
res += parseInt(matches[i],0);
}
$('#res').html(res);
See this working fiddle

Related

Return multiple strings from function based on variable number

I have a string
var str = 'string'
I have a multiplier
var mult = 3
I want to return stringstringstring
The mult will change. Basically mult is kind of like a power but this is a string not a number. And I need to return multiple strings. I'm thinking of looping where mult = the number of times to loop and each would conceptually 'push' but I don't want an array or something like =+ but not a number. I'm thinking I could have the output push to an array the number of times = to mult, and then join the array - but I don't know if join is possible without a delimiter. I'm new at javascript and the below doesn't work but it's what I'm thinking. There's also no ability to input a function in the place I'm running javascript and also no libraries.
var loop = {
var str = 'string'
var arr = [];
var mult = 3;
var i = 0
for (i = 0, mult-1, i++) {
arr.push('string'[i]);
}
}
var finalString = arr.join(''); // I don't know how to get it out of an object first before joining
Not sure if what I want is ridiculous or if it's at all possible
You mean something like below,
var str = 'string'
var mult = 3
var str2 = ''
for(i = 0; i < mult; i++) {
str2 += str
}
console.log(str2)
var str = 'string'
var mult = 3;
var sol =""
while(mult--) {
sol +=str;
}
console.log(sol)
Using resusable function:
const concatStr= (str, mult)=>{
var sol =""
while(mult--) {
sol +=str;
}
console.log(sol)
}
concatStr("string",3)
Using the inbuilt Array.from method:
var str = "string"
var mult = 3
var sol = Array.from({length: mult}, ()=> str).join("")
console.log(sol)
function concatString(str, mult) {
var result = ''
for(i = 0; i < mult; i++) {
result = result.concat(str);
}
return result;
}
const value = concatString('string', 3);
console.log(value);
Also you can use array inbuilt methods,
const mult = 3, displayVal = 'str';
Array(mult).fill(displayVal).join('');
// the string object has a repeat method
console.log('string'.repeat(3));

Get a particular string from the input string

I need to extract a particular string in javascript of format: “STATE: ip reachable” from another set of string I have as input.
From the extracted string, I need to extract both the numbers.
I have done so far is:
var str=<the input value>;
if(str.contains("STATE"))
{
var str = str.substring(str.indexOf("STATE"), string.indexOf("reachable");
}
I am finding difficulty in how to extract the numbers.
I don't really understand what are the 'numbers', but I tried that :
var str= "lorem ipsum STATE: 10.0.5.2 120.30.66.8 test ... blabla bla";
str = str.slice(str.indexOf("STATE"), str.length);
var tab = str.split(" ");
var num1 = tab[1];
var num2 = tab[2];
Use a regular expression...something like this:
var test = "STATE 10.0.0.18 192.168.42.9 reachable";
var ips = test.match(/(\d+\.\d+\.\d+\.\d+)/g);
for (i = 0; i < ips.length; i++) {
document.write(ips[i]);
document.write("<br>");
}
If you are sure about the pattern in the string, you can use below code :
var str = "STATE 10.0.0.18 192.168.42.9 reachable";
if (str.indexOf("STATE") >= 0) {
var str = str.substring(str.indexOf("STATE ")+6, str.indexOf(" reachable"));
var arrIP = str.split(" ");
for (i = 0; i < arrIP.length; i++) {
alert(arrIP[i]);
}
}
jsfiddle : https://jsfiddle.net/nikdtu/4nx50b81/

Word count is incorrect when multiple spaces are present in the string

This function works fine.
But if i add more spaces in str than it gives the wrong count of words. Any help would be appreciated.
str = "coune me in"
var obj = {};
var regex = /[\s]/gi
function count(str){
// total spaces in a string
var spacesCount = str.match(regex).length;
// words count
var wordsCount = str.split(' ').length;
//charetcers count
var charsCount = str.split('').join('').length;
//average count
var avgCount = str.split(' ').join('').length/wordsCount;
// adding it to the object
obj.words = wordsCount;
obj.chars = charsCount;
obj.avgLength = avgCount;
obj.spaces = spacesCount;
return obj
}
count(str)
Try something like:
mystring.split(/\s+/);
This will split on one or more white-space characters so two spaces (or more) in a row will be treated as just one split.
let Allah = 'Allah is our creator.'
Allah = Allah.trim();
count = 0;
for (let i = 0; i < Allah.length; i++) {
let char = Allah[i];
if (char == " " && Allah[i-1] != " ") {//add here
count++;
}
}
count++;
console.log(count);
//output:4

How to get numbers from string in Javascript?

I have a strings that can look like this:
left 10 top 50
How can i extract the numbers, while the numbers can range from 0 to 100 and words can be left/right top/bottom? Thanks
Try match()
var text = "top 50 right 100 left 33";
var arr = text.match(/[0-9]{1,3}/g);
console.log(arr); //Returns an array with "50", "100", "33"
You can also use [\d+] (digits) instead of [0-9]
Place this string in a var, if you know every number will be seperated by a space you can easely do the following:
var string = "top 50 left 100";
// split at the empty space
string.split(" ");
var numbers = new Array();
// run through the array
for(var i = 0; i < string.length; i++){
// check if the string is a number
if(parseInt(string[i], 10)){
// add the number to the results
numbers.push(string[i]);
}
}
Now you can wrap the whole bit in a function to run it at any time you want:
function extractNumbers(string){
var temp = string.split(" ");
var numbers = new Array();
for(var i = 0; i < temp.length; i++){
if(parseInt(temp[i], 10)){
numbers.push(temp[i]);
}
}
return numbers;
}
var myNumbers = extractNumbers("top 50 left 100");
Update
After reading #AmirPopovich s answer, it helped me to improve it a bit more:
if(!isNaN(Number(string[i]))){
numbers.push(Number(string[i]));
}
This will return any type of number, not just Integers. Then you could technically extend the string prototype to extract numbers from any string:
String.prototype.extractNumbers = function(){ /*The rest of the function body here, replacing the keyword 'string' with 'this' */ };
Now you can do var result = "top 50 right 100".extractNumbers();
Split and extract the 2nd and 4th tokens:
var arr = "left 10 top 50".split(" ");
var a = +arr[1];
var b = +arr[3];
var str = 'left 10 top 50';
var splitted = str.split(' ');
var arr = [];
for(var i = 0 ; i < splitted.length ; i++)
{
var num = Number(splitted[i]);
if(!isNaN(num) && num >= 0 && num <= 100){
arr.push(num);
}
}
console.log(arr);
JSFIDDLE
If you want it dynamically by different keywords try something like this:
var testString = "left 10 top 50";
var result = getNumber("top", testString);
function getNumber(keyword, testString) {
var tmpString = testString;
var tmpKeyword = keyword;
tmpString = tmpString.split(tmpKeyword + " ");
tmpString = tmpString[1].split(' ')[0];
return tmpString;
}
var myArray = "left 10 top 50".split(" ");
var numbers;
for ( var index = 0; index < myArray.length; index++ ) {
if ( !isNaN(myArray[index]))
numbers= myArray[index]
}
find working example on the link below
http://jsfiddle.net/shouvik1990/cnrbv485/

Javascript extract unknown number in string

I have a string ctl00_ContentPlaceHolder1_lstViewFormulas_ctrl06_lblCountDown that will come into a javascript function using sender from my asp.net button control...
<asp:Button ID="buttStartTimer" runat="server" CausesValidation="false" OnClientClick="javascript:countdown(this);" Text="Start" />
function test(sender) {
}
The need to get the number directly following ctrl, In the example above it would be 06 (ctrl06_lblCountDown)
How can I extract this number using javascript?
Thanks
var str = "ctl00_ContentPlaceHolder1_lstViewFormulas_ctrl06_lblCountDown",
result = str.match(/.*ctrl(\d+).*/)[1];
Working example: http://jsfiddle.net/RXGb2/
You can extract is using regex easily:
var str = "ctl00_ContentPlaceHolder1_lstViewFormulas_ctrl06_lblCountDown";
var num = parseInt(str.match(/_ctrl([\d]*)_/)[1], 10);
Safer way:
var str = "ctl00_ContentPlaceHolder1_lstViewFormulas_ctrl06_lblCountDown";
var parts = str.match(/_ctrl([\d]*)_/), num;
if(parts.length > 1) {
num = parseInt(parts[1], 10);
}
You could try something like this:
var str = 'ctrl06_lblCountDown',
numericArray = [],
numericString,
num,
i=0,
len = 0;
numericArray = str.match(/[0-9]/g);
len = numericArray.length;
numericString = '';
for(i=0; i<len; i++){
numericString += numericArray[i];
}
num = parseInt(numericString,10);

Categories