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));
Related
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
}
In JavaScript, let's say I have a String like "23+var-5/422*b".
I want to split this String so that I get [23,+,var,-,5,/,422,*,b].
I want to tokenize it so that I split the string into 3 types of tokens:
Numerical literals, [0-9].
String literals, [A-z].
Operator characters, [-+*/].
So basically, go through the string, and for each "cluster of characters" that share the same class (each with 1 or more characters), convert that into a token.
I could probably use a for loop, comparing each character with each class, and manually create a token every time the current "character class" changes... it would be very tedious and use many variables and loops.
Does anyone know a more elegant (less verbose) way to get there?
A global regexp match will do this for you:
var str = "23+var-5/422*b";
var arr = str.match(/[0-9]+|[a-zA-Z]+|[-+*/]/g); // notice the creation of one token
// per operator (even if consecutive)
However, it simply ignores invalid characters instead of erroring out.
Here's a way to do it using Regex. Obviously the code can be simplified more if you use Underscore.js or CoffeeScript. So here's a longer version using vanilla JS:
var s = "23+var-5/422*b"; // your string
var re1 = /[0-9]/; // Regex for numerals
var re2 = /[a-zA-Z]/; // Regex for roman chars
var re3 = /[-+*\/]/; // Regex you wanted for operators
// Helper function, return true if n none-negative
function nonNegative(n) {
return n >= 0;
}
// helper function: add any none-negative n to array arr
function addNonNegative(n, arr) {
if (nonNegative(n)) {arr.push(n)};
}
// The main function to split string s
function split(s) {
var result = []; // The result array, initialized
// Do while string s is none empty.
while(s.length > 0) {
// The order of indices of regex found
var order = [];
// search for index or which the regex occurs, then if that index is none-negative, add it to the 'order' array
addNonNegative(s.search(re1), order);
addNonNegative(s.search(re2), order);
addNonNegative(s.search(re3), order);
// sort the order array
order = order.sort();
// variables to slice the string s.
// start is always 0. Marks the starting index of the first matched regex
var start = order.shift();
// Marks the starting index of the second matched regex
var end = order.shift(); // end is the second result in order
result.push(s.slice(start, end)); // slice the string s from start to end
// update s so that exclude what was sliced before
s = s.slice(end);
// boundary condition: finally when end is null once all regex have been pulled, set s = ""
if (end == null) {s = ""};
}
return result;
}
This question already has answers here:
How do I split a string with multiple separators in JavaScript?
(25 answers)
Closed 8 years ago.
How do I split a string with multiple separators in JavaScript? I'm trying to split on both commas and : colon but, js's split function only supports one separator.
Example :
materialA:125,materialB:150,materialC:175
I want to split both these values into array like
materiaA,materialB,materialC
and second
125,150,175
Or anybody can give me idea how could I multiply these numbers with a constant to get like
materialA:1250, materialB:1500,materialC:1750.
You can split with more than one seperator if you're using regex:
.split(/:|,/)
This would give
["materialA", "125", "materialB", "150", "materialC", "175"]
Changing the approach completely, if all you want to do is multiply all the numbers in your string by a fixed coefficient, you can use string.replace:
var string = "materialA:125,materialB:150,materialC:175";
var coef = 10;
var result = string.replace(/\d+/g, function(match){
return parseInt(match)*coef;
});
Then print(result) outputs the string
materialA:1250,materialB:1500,materialC:1750
\d is a shortcut for [0-9].
Example using #mitim's method:
var str = 'materialA:125,materialB:150,materialC:175',
multiplier = 2;
str = str.split(',').map(function (elem) {
var parts = elem.split(':');
parts[1] *= multiplier;
return parts.join(':');
}).join(',');
This will give you:
materialA:250,materialB:300,materialC:350
You could split the string by comma first, then loop through the resulting array. In that array, each entry would be something like "materialA:125". From there, you can split by the colon and append each part to its own list to work with or if you prefer, just multiply the second half (cast to int first) and rejoin it in to your original string.
Even though someone gave a much better answer, here's a bit of code that does what I mentioned above (since you asked)
var inputString = "materialA:125,materialB:150,materialC:175";
var mats = new Array();
var numbers = new Array();
var temp;
var elements = inputString.split(",");
for(var element in elements){
temp = elements[element].split(":");
mats.push(temp[0]);
numbers.push(parseInt(temp[1]));
}
console.log(mats); // prints ["materialA", "materialB", "materialC"]
console.log(numbers); // prints [125, 150, 175]
You could simply use following Regex:
/[:,]/
And following string method:
mystring = 'materialA:125,materialB:150,materialC:175';
result = mystring.split(/[:,]/);
Here is a Fiddle.
I want to take two values from string
"105.106"
The values 105 and 106 can be different the point(.) will decide their splitting after split i want these values in variable. i have look it into indexOf and split method but not getting logic.
It's quite simple:
var str = "105.106";
var values = str.split('.'); // (or "." or /\./)
console.log(values[0]); // Output: 105
console.log(values[1]); // Output: 106
Live demo.
You can learn more about how split works here. In short, split is a method on the String's prototype that you pass it the character that acts as a delimiter, and it tokenizes the string based on that character. For example, if you had "123,456,789" and you wanted to tokenize the string as if the , was the delimiter, you would get "123", "456", and "789".
Now your string is "105.106", and you want . to act as the delimiter, as such you write something similar to:
tokens = "105.106".split(".");
tokens[0] == "105"; // true
tokens[1] == "106"; // true
As you can see, split has decomposed the string into an array with two components, containing the string splited by the . character.
You can do:
var str = "105.106";
// does the string contain floating point dot ?
if (str.indexOf('.') >= 0) {
var values = str.split('.');
alert(values[0]); // value before dot
alert(values[1]); // value after dot
}
else {
alert(str); // string did not contain a dot/point
}
Above code will give you both values before and after dot/point in case it contains a dot else it will give you string as it was.
The JavaScript String.split(delimiter) method does what you want. Use it like this:
var s = "105.106";
var values = s.split(".");
// values[0] = "105", values[1] = "106".
I've not tested it but guess this may work
var str="xxx.xxxxx";
dot=str.lastIndexOf('.');
num2=str.substring(dot+1);
num1=str.substring(0,dot);
If I have a string like "something12" or "something102", how would I use a regex in javascript to return just the number parts?
Regular expressions:
var numberPattern = /\d+/g;
'something102asdfkj1948948'.match( numberPattern )
This would return an Array with two elements inside, '102' and '1948948'. Operate as you wish. If it doesn't match any it will return null.
To concatenate them:
'something102asdfkj1948948'.match( numberPattern ).join('')
Assuming you're not dealing with complex decimals, this should suffice I suppose.
You could also strip all the non-digit characters (\D or [^0-9]):
let word_With_Numbers = 'abc123c def4567hij89'
let word_Without_Numbers = word_With_Numbers.replace(/\D/g, '');
console.log(word_Without_Numbers)
For number with decimal fraction and minus sign, I use this snippet:
const NUMERIC_REGEXP = /[-]{0,1}[\d]*[.]{0,1}[\d]+/g;
const numbers = '2.2px 3.1px 4px -7.6px obj.key'.match(NUMERIC_REGEXP)
console.log(numbers); // ["2.2", "3.1", "4", "-7.6"]
Update: - 7/9/2018
Found a tool which allows you to edit regular expression visually: JavaScript Regular Expression Parser & Visualizer.
Update:
Here's another one with which you can even debugger regexp: Online regex tester and debugger.
Update:
Another one: RegExr.
Update:
Regexper and Regex Pal.
If you want only digits:
var value = '675-805-714';
var numberPattern = /\d+/g;
value = value.match( numberPattern ).join([]);
alert(value);
//Show: 675805714
Now you get the digits joined
I guess you want to get number(s) from the string. In which case, you can use the following:
// Returns an array of numbers located in the string
function get_numbers(input) {
return input.match(/[0-9]+/g);
}
var first_test = get_numbers('something102');
var second_test = get_numbers('something102or12');
var third_test = get_numbers('no numbers here!');
alert(first_test); // [102]
alert(second_test); // [102,12]
alert(third_test); // null
IMO the #3 answer at this time by Chen Dachao is the right way to go if you want to capture any kind of number, but the regular expression can be shortened from:
/[-]{0,1}[\d]*[\.]{0,1}[\d]+/g
to:
/-?\d*\.?\d+/g
For example, this code:
"lin-grad.ient(217deg,rgba(255, 0, 0, -0.8), rgba(-255,0,0,0) 70.71%)".match(/-?\d*\.?\d+/g)
generates this array:
["217","255","0","0","-0.8","-255","0","0","0","70.71"]
I've butchered an MDN linear gradient example so that it fully tests the regexp and doesn't need to scroll here. I think I've included all the possibilities in terms of negative numbers, decimals, unit suffixes like deg and %, inconsistent comma and space usage, and the extra dot/period and hyphen/dash characters within the text "lin-grad.ient". Please let me know if I'm missing something. The only thing I can see that it does not handle is a badly formed decimal number like "0..8".
If you really want an array of numbers, you can convert the entire array in the same line of code:
array = whatever.match(/-?\d*\.?\d+/g).map(Number);
My particular code, which is parsing CSS functions, doesn't need to worry about the non-numeric use of the dot/period character, so the regular expression can be even simpler:
/-?[\d\.]+/g
var result = input.match(/\d+/g).join([])
Using split and regex :
var str = "fooBar0123".split(/(\d+)/);
console.log(str[0]); // fooBar
console.log(str[1]); // 0123
The answers given don't actually match your question, which implied a trailing number. Also, remember that you're getting a string back; if you actually need a number, cast the result:
item=item.replace('^.*\D(\d*)$', '$1');
if (!/^\d+$/.test(item)) throw 'parse error: number not found';
item=Number(item);
If you're dealing with numeric item ids on a web page, your code could also usefully accept an Element, extracting the number from its id (or its first parent with an id); if you've an Event handy, you can likely get the Element from that, too.
As per #Syntle's answer, if you have only non numeric characters you'll get an Uncaught TypeError: Cannot read property 'join' of null.
This will prevent errors if no matches are found and return an empty string:
('something'.match( /\d+/g )||[]).join('')
Here is the solution to convert the string to valid plain or decimal numbers using Regex:
//something123.777.321something to 123.777321
const str = 'something123.777.321something';
let initialValue = str.replace(/[^0-9.]+/, '');
//initialValue = '123.777.321';
//characterCount just count the characters in a given string
if (characterCount(intitialValue, '.') > 1) {
const splitedValue = intitialValue.split('.');
//splittedValue = ['123','777','321'];
intitialValue = splitedValue.shift() + '.' + splitedValue.join('');
//result i.e. initialValue = '123.777321'
}
If you want dot/comma separated numbers also, then:
\d*\.?\d*
or
[0-9]*\.?[0-9]*
You can use https://regex101.com/ to test your regexes.
Everything that other solutions have, but with a little validation
// value = '675-805-714'
const validateNumberInput = (value) => {
let numberPattern = /\d+/g
let numbers = value.match(numberPattern)
if (numbers === null) {
return 0
}
return parseInt(numbers.join([]))
}
// 675805714
One liner
I you do not care about decimal numbers and only need the digits, I think this one liner is rather elegant:
/**
* #param {String} str
* #returns {String} - All digits from the given `str`
*/
const getDigitsInString = (str) => str.replace(/[^\d]*/g, '');
console.log([
'?,!_:/42\`"^',
'A 0 B 1 C 2 D 3 E',
' 4 twenty 20 ',
'1413/12/11',
'16:20:42:01'
].map((str) => getDigitsInString(str)));
Simple explanation:
\d matches any digit from 0 to 9
[^n] matches anything that is not n
* matches 0 times or more the predecessor
( It is an attempt to match a whole block of non-digits all at once )
g at the end, indicates that the regex is global to the entire string and that we will not stop at the first occurrence but match every occurrence within it
Together those rules match anything but digits, which we replace by an empty strings. Thus, resulting in a string containing digits only.