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/
Related
I need to count numbers in a string. The numbers are separated by spaces.
(1 2 3 4 10) I was trying to do this by charAt by that doesnt work if the number is not a single digit. I am relative new to JS and need some examples. I started with this but ran into a double digit #:
string1 = (1 1 1 4 10)
var total = parseFloat(0);
for(var j=0; j<string1.length; j++) {
total += parseFloat(string1.charAt(j));
}
Any help would be appreciated
I don't know why you need to do this way, but if this string comes from another font, you can deal with it, something like this:
var string1 = "(1 1 1 4 10)";
var aux = string1.replace("(","").replace(")","");
aux = aux.split(" ");
var total = parseFloat(0);
for(var j=0; j<aux.length; j++) {
total += parseFloat(aux[j]);
}
console.log(total);
https://jsfiddle.net/bggLkvxd/1/
Create an array:
var arr=[1,2,3]
and then do:
var count=0;
arr.forEach(function(number){
count+=number;
}
Or use a string:
var str="1 2 3";
var arr=str.split(" ");
var count=0;
arr.forEach(function(number){
count+=parseInt(number);
}
Count now contains the sum of all chars
// use method split to convert string to array and then add array items:
var string1 = "1 1 1 4 10", total = 0;
string1.split(" ").forEach(function(item) {
total += +item;
});
Here's a simpler way. First, fix string1 so it's actually a string (by adding " "s), also properly declare it with "var string". Then you could do something like this.
var string1 = ("1 1 1 4 10")
function addString(input) {
var sum = 0; //get your empty variable ready
var array1 = input.split(" "); //split your string into an array
for(var i=0; i<array1.length; i++) {
array1[i] = parseInt(array1[i]); // each new array element is integer
sum += array1[i]; // += is operator for solve/refactor
}
return sum;
}
addString(string1);
I have a string contains just numbers. Something like this:
var numb = "5136789431235";
And I'm trying to match ascending numbers which are two or more digits. In string above I want this output:
var numb = "5136789431235";
// ^^^^ ^^^
Actually I can match a number which has two or more digits: /[0-9]{2,}/g, But I don't know how can I detect being ascending?
To match consecutive numbers like 123:
(?:(?=01|12|23|34|45|56|67|78|89)\d)+\d
RegEx Demo
To match nonconsecutive numbers like 137:
(?:(?=0[1-9]|1[2-9]|2[3-9]|3[4-9]|4[5-9]|5[6-9]|6[7-9]|7[8-9]|89)\d)+\d
RegEx Demo
Here is an example:
var numb = "5136789431235";
/* The output of consecutive version: 6789,123
The output of nonconsecutive version: 136789,1234
*/
You could do this by simply testing for
01|12|23|34|45|56|67|78|89
Regards
You just need to loop through each number and check next one. Then add that pair of values to a result variable:
var numb = "5136789431235";
var res = [];
for (var i = 0, len = numb.length; i < len-1; i++) {
if (numb[i] < numb[i+1]) res.push(new Array(numb[i],numb[i+1]))
}
res.forEach(function(k){console.log(k)});
Here is fiddle
Try this to match consecutive numbers
var matches = [""]; numb.split("").forEach(function(val){
var lastNum = 0;
if ( matches[matches.length-1].length > 0 )
{
lastNum = parseInt(matches[matches.length-1].slice(-1),10);
}
var currentNum = parseInt(val,10);
if ( currentNum == lastNum + 1 )
{
matches[matches.length-1] += String(currentNum);
}
else
{
if ( matches[matches.length-1].length > 1 )
{
matches.push(String(currentNum))
}
else
{ matches[matches.length-1] = String(currentNum);
}
}
});
matches = matches.filter(function(val){ return val.length > 1 }) //outputs ["6789", "123"]
DEMO
var numb = "5136789431235";
var matches = [""]; numb.split("").forEach(function(val){
var lastNum = 0;
if ( matches[matches.length-1].length > 0 )
{
lastNum = parseInt(matches[matches.length-1].slice(-1),10);
}
var currentNum = parseInt(val,10);
if ( currentNum == lastNum + 1 )
{
matches[matches.length-1] += String(currentNum);
}
else
{
if ( matches[matches.length-1].length > 1 )
{
matches.push(String(currentNum))
}
else
{ matches[matches.length-1] = String(currentNum);
}
}
});
matches = matches.filter(function(val){ return val.length > 1 }) //outputs ["6789", "123"]
document.body.innerHTML += JSON.stringify(matches,0,4);
Do you have to use Regex?
Not sure if the most efficient, but since they're always going to be numbers, could you split them up into an array of numbers, and then do an algorithm on that to sort through?
So like
var str = "123456";
var res = str.split("");
// res would equal 1,2,3,4,5,6
// Here do matching algorithm
Not sure if this is a bad way of doing it, just another option to think about
I've did something different on a fork from jquery.pwstrength.bootstrap plugin, using substring method.
https://github.com/andredurao/jquery.pwstrength.bootstrap/commit/614ddf156c2edd974da60a70d4945a1e05ff9d8d
I've created a string containing the sequence ("123456789") and scanned the sequence on a sliding window of size 3.
On each scan iteration I check for a substring of the window on the string:
var numb = "5136789431235";
//check for substring on 1st window => "123""
"5136789431235"
ˆˆˆ
How do I square a number's digits? e.g.:
square(21){};
should result in 41 instead of 441
This is easily done with simple math. No need for the overhead of string processing.
var result = [];
var n = 21;
while (n > 0) {
result.push(n%10 * n%10);
n = Math.floor(n/10);
}
document.body.textContent = result.reverse().join("");
In a loop, while your number is greater than 0, it...
gets the remainder of dividing the number by 10 using the % operator
squares it and adds it to an array.
reduces the original number by dividing it by 10, dropping truncating to the right of the decimal, and reassigning it.
Then at the end it reverses and joins the array into the result string (which you can convert to a number if you wish)
I think he means something like the following:
var output = "";
for(int i = 0; i<num.length; i++)
{
output.concat(Math.pow(num[i],2).toString());
}
I believe this is what the OP is looking for? The square of each digit?
var number = 12354987,
var temp = 0;
for (var i = 0, len = sNumber.length; i < len; i += 1) {
temp = String(number).charAt(i);
output.push(Number(temp) * Number(temp));
}
console.log(output);
Split the string into an array, return a map of the square of the element, and rejoin the resulting array back into a string.
function squareEachDigit(str) {
return str.split('').map(function (el) {
return (+el * +el);
}).join('');
}
squareEachDigit('99') // 8181
squareEachDigit('52') // 254
DEMO
function sq(n){
var nos = (n + '').split('');
var res="";
for(i in nos){
res+= parseInt(nos[i]) * parseInt(nos[i]);
}
return parseInt(res);
}
var result = sq(21);
alert(result)
You'll want to split the numbers into their place values, then square them, then concatenate them back together. Here's how I would do it:
function fn(num){
var strArr = num.toString().split('');
var result = '';
for(var i = 0; i < strArr.length; i++){
result += Math.pow(strArr[i], 2) + '';
}
return +result;
}
Use Math.pow to square numbers like this:
Math.pow(11,2); // returns 121
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
I've got a string!
7 serpents
4 bikes
2 mangoes
It's made up of number + [space] + thing-string. I need to be able to order the whole string with reference to the number. So it should come out:
2 mangoes
4 bikes
7 serpents
It's a simple bubble sort for the number and then cross-referencing the index to get the final order. The JavaScript code below works, but I can't help but think it could be made more efficient. Am I missing a trick here??
And remember: I'm an artist, so I code in crayon!
var eventsStr = "7 serpents\n4 bikes\n2 mangoes"
var splitArr = eventsStr.split("\n")
var numArray = new Array();
var events = new Array();
for (var i = 0; i < splitArr.length; i++)
{
var temp = splitArr[i] ;
var part1 = temp.substring(0, temp.indexOf(" "))
var part2 = temp.substring(temp.indexOf(" ")+1, temp.length)
numArray[i] = part1;
events[i] = part2;
}
var sorted = superCopy(numArray);
var sorted = sorted.sort(sortArrayNumerically);
alert(getOrder(sorted, numArray, events))
function getOrder(orderedarr, arr1, arr2)
{
var str = "";
for (var i = 0; i < arr1.length; i++)
{
for (var j = 0; j < orderedarr.length; j++)
{
if (arr1[i] == orderedarr[j])
{
// found the thing !what is the event?
str += arr1[i] + " " + arr2[i] + "\n";
}
}
}
return str
}
function sortArrayNumerically(a,b)
{
return a - b;
}
function superCopy(arr)
{
tempArr = new Array();
for (var i = 0; i < arr.length; i++)
{
tempArr[i] = arr[i]
}
return tempArr
}
You could use JavaScript's sort() function:
eventsStr.split('\n').sort().join('\n');
eventsStr.split('\n') - first split the string on the newline character to create an array
.sort() - then use the sort() function to sort the array
.join('\n') - then put the string back together, joining the array elements with a newline between them
Reference:
String.prototype.split()
Array.prototype.sort()
Array.prototype.join()
This is an alphabetic sort though, so if your string contained, say, 12 mangoes, the result would not be sorted numerically. To sort numerically, you could do something like this:
eventsStr.split('\n').sort(function(a, b) {
return parseInt(a.split(' ')[0], 10) > parseInt(b.split(' ')[0], 10);
}).join('\n');
In this situation, the sort() function is called with a callback parameter, taking 2 values: the first string to be compared and the second string to be compared. This callback function then splits the string, extracts the number and compares it with the number in the other string.
Use
splitArr.sort() // as per your code
DEMO
var eventsStr = "7 serpents\n4 bikes\n2 mangoes"
arr = eventsStr.split('\n')
# ["7 serpents", "4 bikes", "2 mangoes"]
arr
# ["7 serpents", "4 bikes", "2 mangoes"]
arr.sort()
# ["2 mangoes", "4 bikes", "7 serpents"]