How to extract last characters of type number javascript/jquery - javascript

I have some strings like:
row_row1_1,
row_row1_2,
row_row1_13,
row_row1_287,
...
and I want to take the last numbers of that strings, ut can be 1, 2, 13 or 287. That strings are generated automatically and I can't control if there is going to be 1 number, 2 numbers, 3 numbers...
I would like to make a function that takes the last number character, or the numbers after the second '_' character. is there any idea?
Thank you very much!

If your strings always follow this pattern str_str_str then you can use the split method and get the 2ยบ index of the array, like this:
var number = str.split('_')[2];

As #PaulS said, you can always use regex for that purpose:
var getLastNumbers = function(str)
{
return str.replace(/.+(_)/, '');
};
getLastNumbers("row_row1_287"); // Will result -> 287
Fiddle

Taking the last numeric characters
function getNumericSuffix(myString) {
var reversedString = myString.split('').reverse().join('');
var i, result="";
for(i = 0; i < reversedString.length; i++) {
if(!isNaN(reversedString[i])) {
result = reversedString[i] + result;
} else break;
}
return parseInt(result); // assuming all number are integers
}

Related

Why does 'duplicates' property keeps returning 3 instead of 2?

The task I am undertaking is as follows:
The function should be called removeDuplicates and should return an object literal containing a 'uniques' property, which should be the sorted input string but without any duplicates or special characters.
The returned object should also have a 'duplicates' property which should represent the total number of duplicate characters dropped.
So:
removeDuplicates('th#elex_ash?')
should return:
{uniques: 'aehlstx', duplicates: 2}
Here is my code:
function removeDuplicates(str) {
var stg = str.split("");
var nstr = [];
var allowed = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
var count = 0;
for(var i = 0; i<stg.length;i++){
if(nstr.indexOf(stg[i])== -1){
if(allowed.indexOf(stg[i]) > -1){
nstr.push(str[i])
}
else{
count +=1;
}
}
}
return{uniques: nstr.sort().join(""),duplicates: count}
}
But the result returns {uniques: 'aehlstx', duplicates: 3} instead.
You are checking first if you've seen the character before, and THEN checking it was an allowed character and counting the number of times you see a non-allowed character.
You need to check if the character is allowed, and then see if you've seen it before.
Because you are counting the not allowed characters :)

Adding numbers within a string

I want to take a string of numbers and characters and add up the numbers.
For example: "In 2015, I want to know how much does iPhone 6+ cost?"
Output: 2021
Here is my current code:
var str = "In 2015, I want to know how much does iPhone 6+ cost?";
function sumFromString(str){
var punctuationless = str.replace(/['!"#$%&\\'()\*+,\-\.\/:;<=>?#\[\\\]\^_`{|}~']/g,"");
var finalString = punctuationless.replace(/\s{2,}/g," ");
var StringList = finalString.split(" ");
var sum = [];
for (i = 0; i < StringList.length; i++)
if (isInt(StringList[i])
sum.add(StringList[i]);
sum.reduce( (prev, curr) => prev + curr );
}
sumFromString(str);
My code takes a string and strips it of punctuation and then places each individual word/number into the array, StringList.
I can't get the next part to work.
What I tried was to iterate through each value in the array. The if statement is supposed to check if the array element is an integer. If so, it will add the integer to an empty array called sum. I then add all the values of the array, sum, together.
Much simpler:
function sumFromString(str) {
return (str.match(/\d+/g)||[]).reduce((p,c)=>+c+p);
}
Note in particular that I use +c+p - +c casting the current value from a string to a number, then adding it to p. This matches all the numbers in the string - getting an empty array if there were none - and reduces that.
For the sake of variety, here's a way to do it without regular expressions:
var myString = "5 bunnies ate 6 carrots in 2days.";
var myArray = myString.split('');
var total = 0;
for (var i = 0; i < myArray.length; i++) {
if (!isNaN(parseInt(myArray[i]))) {
total += parseInt(myArray[i]);
}
}
Fiddle Demo
note: If there's a chance myString could be null, you'd want to add a check before the split.
Split the string into an array of all characters with the split function and then run the filter function to get all numbers. Use the map function to go through all elements that include numbers, and delete characters from them that aren't digits.
Then use reduce to get the sum of all numbers. Since we're dealing with strings here, we have to perform type conversion to turn them into numbers.
string.split(' ').filter(function(word) {
return /\d+/.test(word) }
}).map(function(s) {
return s.replace(/\D/, '')
}).reduce(function(a,b) {
return Number(a) + Number(b);
});

JavaScript split string by regex

I will have a string never long than 8 characters in length, e.g.:
// represented as array to demonstrate multiple examples
var strs = [
'11111111',
'1RBN4',
'12B5'
]
When ran through a function, I would like all digit characters to be summed to return a final string:
var strsAfterFunction = [
'8',
'1RBN4',
'3B5'
]
Where you can see all of the 8 single 1 characters in the first string end up as a single 8 character string, the second string remains unchanged as at no point are there adjacent digit characters and the third string changes as the 1 and 2 characters become a 3 and the rest of the string is unchanged.
I believe the best way to do this, in pseudo-code, would be:
1. split the array by regex to find multiple digit characters that are adjacent
2. if an item in the split array contains digits, add them together
3. join the split array items
What would be the .split regex to split by multiple adajcent digit characters, e.g.:
var str = '12RB1N1'
=> ['12', 'R', 'B', '1', 'N', '1']
EDIT:
question:
What about the string "999" should the result be "27", or "9"
If it was clear, always SUM the digits, 999 => 27, 234 => 9
You can do this for the whole transformation :
var results = strs.map(function(s){
return s.replace(/\d+/g, function(n){
return n.split('').reduce(function(s,i){ return +i+s }, 0)
})
});
For your strs array, it returns ["8", "1RBN4", "3B5"].
var results = string.match(/(\d+|\D+)/g);
Testing:
"aoueoe34243euouoe34432euooue34243".match(/(\d+|\D+)/g)
Returns
["aoueoe", "34243", "euouoe", "34432", "euooue", "34243"]
George... My answer was originally similar to dystroy's, but when I got home tonight and found your comment I couldn't pass up a challenge
:)
Here it is without regexp. fwiw it might be faster, it would be an interesting benchmark since the iterations are native.
function p(s){
var str = "", num = 0;
s.split("").forEach(function(v){
if(!isNaN(v)){
(num = (num||0) + +v);
} else if(num!==undefined){
(str += num + v,num = undefined);
} else {
str += v;
}
});
return str+(num||"");
};
// TESTING
console.log(p("345abc567"));
// 12abc18
console.log(p("35abc2134mb1234mnbmn-135"));
// 8abc10mb10mnbmn-9
console.log(p("1 d0n't kn0w wh#t 3153 t0 thr0w #t th15 th1n6"));
// 1d0n't0kn0w0wh#t12t0thr0w0#t0th6th1n6
// EXTRY CREDIT
function fn(s){
var a = p(s);
return a === s ? a : fn(a);
}
console.log(fn("9599999gh999999999999999h999999999999345"));
// 5gh9h3
and here is the Fiddle & a new Fiddle without overly clever ternary

RegEx for filling up string

I have the following input:
123456_r.xyz
12345_32423_131.xyz
1235.xyz
237213_21_mmm.xyz
And now I need to fill up the first connected numbers to 8 numbers leading with 0:
00123456_r.xyz
00012345_32423_131.xyz
00001235.xyz
00237213_21_mmm.xyz
My try was to split a the dot, then split (if existing) at the underscore and get the first numbers and fill them up.
But I think there will be a more efficient way with the regex replace function with just the one function, right? How would this look like?
TIA
Matt
I would use a regex, but just for the spliting :
var input = "12345_32423_131.xyz";
var output = "00000000".slice(input.split(/_|\./)[0].length)+input;
Result : "00012345_32423_131.xyz"
EDIT :
the fast, no-splitting but no-regex, solution I gave in comments :
"00000000".slice(Math.min(input.indexOf('_'), input.indexOf('.'))+1)+input
I wouldn't split at all, just replace:
"123456_r.xyz\n12345_32423_131.xyz\n1235.xyz\n237213_21_mmm.xyz".replace(/^[0-9]+/mg, function(a) {return '00000000'.slice(0, 8-a.length)+a})
There's a simple regexp to find the part of the string you want to replace, but you'll need to use a replace function to perform the action you want.
// The array with your strings
var strings = [
'123456_r.xyz',
'12345_32423_131.xyz',
'1235.xyz',
'237213_21_mmm.xyz'
];
// A function that takes a string and a desired length
function addLeadingZeros(string, desiredLength){
// ...and, while the length of the string is less than desired..
while(string.length < desiredLength){
// ...replaces is it with '0' plus itself
string = '0' + string;
}
// And returns that string
return string;
}
// So for each items in 'strings'...
for(var i = 0; i < strings.length; ++i){
// ...replace any instance of the regex (1 or more (+) integers (\d) at the start (^))...
strings[i] = strings[i].replace(/^\d+/, function replace(capturedIntegers){
// ...with the function defined above, specifying 8 as our desired length.
return addLeadingZeros(capturedIntegers, 8);
});
};
// Output to screen!
document.write(JSON.toString(strings));

How to match with javascript and regex?

I have the following HTML:
<span id="UnitCost5">$3,079.95 to $3,479.95</span>
And i want to use Javascript and Regex to get all number matches.
So i want my script function to return: 3,079.95 AND 3,479.95
Note the text may be different so i need the solution as generic as posible, may be it will be like this:
<span id="UnitCost5">$3,079.95 And Price $3,479.95</span>
All the numbers would be matched by:
\.?\d[\d.,]*
This assumes the numbers you look for can start with a decimal dot. If they cannot, this would work (and maybe produce less false positives):
\d[\d.,]*
Be aware that different local customs exist in number formatting.
I assume that you use appropriate means to get hold of the text value of the HTML nodes you wish to process, and that HTML parsing is not part of the excercise.
You don't want to capture all numbers, otherwise you would get the 5 in the id, too. I would guess, what you're looking for is numbers looking like this: $#,###.##
Here goes the expression for that:
/\$[0-9]{1,3}(,[0-9]{3})*(\.[0-9]+)?/
\$ The dollar sign
[0-9]{1,3} One to three digits
(,[0-9]{3})* [Optional]: Digit triplets, preceded by a comma
(\.[0-9]+)? [Optional]: Even more digits, preceded by a period
/(?:\d{1,3},)*\d{1,3}(?:\.\d+)?/g;
Let's break that into parts for explanations:
(?:\d{1,3},)* - Match any numbers separated by a thousand-divider
\d{1,3} - Match the numbers before the decimal point
(?:.\d+) - Match an arbitrary number of decimals
Flag 'g' - Make a global search to find all matches in the string
You can use it like this:
var regex = /(?:\d{1,3},)*\d{1,3}(?:\.\d+)?/g;
var numbers = "$3,079.95 And Price $3,479.95".match(regex);
// numbers[0] = 3,079.95
// numbers[1] = 3,479.95
A very simple solution is the following one. Note that it will also match some invalid number strings like $..44,.777.
\$[0-9,.]+
(function () {
var reg = /\$([\d\.,]+)\s[\w\W]+\s\$([\d\.,]+)$/;
// this function used to clean inner html
function trim(str) {
var str = str.replace(/^\s\s*/, ''),
ws = /\s/,
i = str.length;
while (ws.test(str.charAt(--i)));
return str.slice(0, i + 1);
}
function getNumbersFromElement(elementId) {
var el = document.getElementById(elementId),
text = trim(el.innerHTML),
firstPrice,
secondPrice,
result;
result = reg.exec(text);
if (result[1] && result[2]) {
// inside this block we have valid prices
firstPrice = result[1];
secondPrice = result[2];
// do whatever you need
return firstPrice + ' AND ' + secondPrice;
} else {
return null; // otherwise
}
}
// usage:
getNumbersFromElement('UnitCost5');
})();
The following will return an array of all prices found in the string
function getPrices(str) {
var reg = /\$([\d,.]+)/g;
var prices =[];
var price;
while((price = reg.exec(str))!=null) {
prices.push(price);
}
return prices;
}
edit: note that the regex itself may return some false positives

Categories

Resources