I am writing following regex for validating Different currency entries in excel sheet format:
/^((\s*[\$]?[+-]?\d*|(\d{0,3}(\s?\d{3})*)(,\d+)?[\$]?(\s*[sSrR]\s*(\d+|(\d+-\d+)))?)|((\s*[\$]?[+-]?\d*|(\d{0,3}(\s?\d{3})*)(,\d+)?[\$]?(\t\s*[\$]?[+-]?\d*|(\d{0,3}(\s?\d{3})*)(,\d+)?[\$]?)*[\n\rx]*)+))$/
This regex is generated by following javascript code:
var groupingSeparator = "\\s"; // For euro currency
var decimalSeparator = ","; // for euro currency
var NUMBER = "\\s*[\\$]?[+-]?\\d*|(\\d{0,3}(" + groupingSeparator + "?\\d{3})*)(" + decimalSeparator + "\\d+)?[\\$]?";
this.basicNumberRegExp = NUMBER;
var REPEAT_NUMBER = NUMBER + "(\\s*[sSrR]\\s*(\\d+|(\\d+-\\d+)))?";
var EXCEL_LINE = NUMBER + "(\\t" + NUMBER + ")*";
var EXCEL_MULTI_LINE = "(" + EXCEL_LINE + "[\\n\\rx]*)+";
var ret = "^((" + REPEAT_NUMBER + ")|(" + EXCEL_MULTI_LINE + "))$";
It should validate following entries:
3r3
-3r3
333
-333
333,33
-333,33
333 333
-333 33
But it is not matching/validating the following value, What is the reason:
-3r3
You missed a pair of parentheses.
You defined
var NUMBER = "\\s*[\\$]?[+-]?\\d*|(\\d{0,3}(" + groupingSeparator + "?\\d{3})*)(" + decimalSeparator + "\\d+)?[\\$]?";
Too long, but it's basically
var NUMBER = "(...) | (...)";
In the statement
var REPEAT_NUMBER = NUMBER + "(\\s*[sSrR]\\s*(\\d+|(\\d+-\\d+)))?";
, REPEAT_NUMBER is defined as
"(...) | (...)(...)?"
which is parsed as (because | has a lower precedence than concatenation)
"(...) | ((...)(...)?)"
Adding a pair of parentheses will work. Define
var NUMBER = "(\\s*[\\$]?[+-]?\\d*|(\\d{0,3}(" + groupingSeparator + "?\\d{3})*)(" + decimalSeparator + "\\d+)?[\\$]?)";
Try it online!
Related
I am trying to complete a Kata whereby I create a phone number from a given array input.
Input: [1,2,3,4,5,6,7,8,9,0]
Output: (123) 456-7890
The issue I have is that once I have built my string, when I call join(''), the commas are not being removed. My results is still: (1,2,3) 4,5,6-7,8,9,0.
What is the issue with the code that is preventing this happening?
function createPhoneNumber(numbers){
var newNum = [];
newNum.push("(" + numbers.slice(0,3) + ")" + " " + numbers.slice(3,6) + "-" + numbers.slice(6,10));
return newNum.join('');
}
It sounds like the numbers parameter is an array:
function createPhoneNumber(numbers) {
var newNum = [];
newNum.push("(" + numbers.slice(0, 3) + ")" + " " + numbers.slice(3, 6) + "-" + numbers.slice(6, 10));
return newNum.join('');
}
console.log(createPhoneNumber('1234567890'.split('')));
In which case .sliceing it will produce another array, from the specified indicies, and using + with an array will result in concatenation. When the array gets implicitly turned into a string, its elements will be joined by a comma.
Join the sliced array while concatenating instead (and don't create a newNum array):
function createPhoneNumber(numbers) {
return "(" + numbers.slice(0, 3).join('') + ")" + " " + numbers.slice(3, 6).join('') + "-" + numbers.slice(6, 10).join('');
}
console.log(createPhoneNumber('1234567890'.split('')));
A nicer option would be to join the numbers into a string first:
function createPhoneNumber(numbers) {
const numStr = numbers.join('');
return `(${numStr.slice(0, 3)}) ${numStr.slice(3, 6)} - ${numStr.slice(6)}`;
}
console.log(createPhoneNumber('1234567890'.split('')));
I would recomment that you use template literals introduced in es6:
function createPhoneNumber(numbers){
const phNo = `(${numbers.slice(0,3)}) ${numbers.slice(3,6)}-${numbers.slice(6,10)}`
return phNo
}
createPhoneNumber('1234567890') // output ==> (123) 456-7890
I'm trying to get Redis data in NodeJS. The Redis data needs to be converted to a dictionary for further processing. I gave it a try but finding difficult as parseFloat on string keeps giving me NaN.
Can anyone please help me to do it the correct way? Variable string has the sample data in below code. Please see the expected results below.
var string = "[ '[Timestamp(\'2018-06-29 15:29:00\'), \'260.20\', \'260.40\', \'260.15\', \'260.30\']' ]";
string = string.replace("[", "");
string = string.replace("]", "");
string = string.replace("[", "");
string = string.replace("]", "");
s1 = string
var array = string.split(",");
var final = "{" + "\"date\"" + ":" + "\"" + array[0] + ",\"Open\"" + ":" + "\"" + array[1].trim() + "\"" + ",\"High\"" + ":" + "\"" + array[2].trim() + "\"" + ",\"Low\"" + ":" + "\"" + array[3].trim() + "\"" + ",\"Close\"" + ":" + "\"" + array[4].trim() + "\"" + "}";
console.log(final);
Expected Result:
{
"date": " Timestamp('2018-06-29 15:29:00')",
"Open": "260.20",
"High": "260.40",
"Low": "260.15",
"Close": "260.30"
}
You have extra apostrophes at both sides of your string which is not needed and while parsing parseFloat("'260.20'")it returns NaN. You could remove them from the array as below:
array = array.map( (str) => str.replace(/'/g, '') );
parseFloat(array[1]); // 260.20
It would probably be a whole lot easier to split the string by single-quotes, then combine into an object:
const string = "[ '[Timestamp(\'2018-06-29 15:29:00\'), \'260.20\', \'260.40\', \'260.15\', \'260.30\']' ]";
const [,,timestamp,,Open,,High,,Low,,Close] = string.split("'");
const obj = {
date: `Timestamp('${timestamp}')`,
Open,
High,
Low,
Close
}
console.log(obj);
Note that \' inside a string delimited by double-quotes doesn't do anything - it's the same as '. (If you need a literal backslash, use \\)
The following is my element id and I want to update it dynamically.
invoice[46][ap_details][4][ap_header_id]
I want to update only second number, i.e. [4], like this:
invoice[46][ap_details][5][ap_header_id]
I am using below code which is updating both the values.
var strNewName = $(this).attr('name').replace(/\[\d+\]/g, function(strName) {
strName = strName.replace(/[\[\]']+/g, '');
var intNumber = parseInt(strName) + 1;
return '[' + intNumber + ']';
});
Any help would be appreciated.
var strName = "invoice[46][ap_details][4][ap_header_id]";
var parts = strName.split('[');
parts[3] = parts[3].replace(/^\d+/, n => +n + 1);
var strNewName = parts.join('[');
console.log(strNewName);
If you don't want to use arrow functions replace this line:
parts[3] = parts[3].replace(/^\d+/, n => +n + 1);
with this:
parts[3] = parts[3].replace(/^\d+/, function(n) { return +n + 1; });
Explanation:
split will return an array like this:
[
"invoice",
"46]", // parts[1] to change this
"ap_details]",
"4]", // parts[3] to change this (and so on, you do the math)
"ap_header_id]"
]
The /^\d+/ will match any number at the begining (no need for the g modifier).
Replace with +n + 1 not n + 1 because n is a string, you have to force the interpretter to use it as a number or otherwise this "4" + 1 will result to this "41".
Then after you change what you want, join the parts using join with the same character you used for splitting ([).
Using this regex /((\w)+)(\[\d+\])(\[(\w)+\])(\[\d+\])(\[(\w)+\])/gi you can construct the string back and change your integer.
var match = /((\w)+)(\[\d+\])(\[(\w)+\])(\[\d+\])(\[(\w)+\])/gi.exec(youString);
//group 6 is your digit.
var newId = parseInt(match[6].replace("\[\]", "")) + 1;
var newString = match[1] + match[3] + match[4] + "[" + newId + "]" + match[7];
Here is a fiddle with the answer https://jsfiddle.net/gzfud9vc/
Maybe dont use regex to build your element id. You can do its as follows as well:
var id = 5
var name = "invoice[46][ap_details][";
name += id;
name += "][ap_header_id]";
var toReplace = "invoice[46][ap_details][~~id~~][ap_header_id]"
var replaced = toReplace.replace(/~~id~~/g, id);
console.log(name);
console.log(replaced);
I have this strange issue, hope that someone will explain what is going on.
My intention is to capture the textual part (a-z, hyphen, underscore) and append the numeric values of id and v to it, underscore separated.
My code:
var str_1 = 'foo1_2';
var str_2 = 'foo-bar1_2';
var str_3 = 'foo_baz1_2';
var id = 3;
var v = 2;
str_1 = str_1.replace(/([a-z_-]+)\d+/,'$1' + id + '_' + v);
str_2 = str_2.replace(/([a-z_-]+)\d+/,'$1' + id + '_' + v);
str_3 = str_3.replace(/([a-z_-]+)\d+/,'$1' + id + '_' + v);
$('#test').html(str_1 + '<br>' + str_2 + '<br>' + str_3 + '<br>');
Expected result:
foo3_2
foo-bar3_2
foo_baz3_2
Actual Result:
foo3_2_2
foo-bar3_2_2
foo_baz3_2_2
Any ideas?
JS Fiddle example
Your pattern:
/([a-z_-]+)\d+/
matches only "foo1" in "foo1_2", and "foo" will be the value of the captured group. The .replace() function replaces the portion of the source string that was actually matched, leaving the remainder alone. Thus "foo1" is replaced by "foo3_2", but the original trailing "_2" is still there as well.
If you want to alter the entire string, then your regular expression will have to account for everything in the source strings.
Just try with:
str_1 = str_1.match(/([a-z_-]+)\d+/)[1] + id + '_' + v;
Use this instead to capture 1_2 completely:
str_1 = str_1.replace(/([a-z_-]+)\d+_\d+/,'$1' + id + '_' + v);
Because you want to replace _2 also of string. Solution can be this:
str_1 = str_1.replace(/([a-z_-]+)\d+_\d/,'$1' + id + '_' + v);
str_2 = str_2.replace(/([a-z_-]+)\d+_\d/,'$1' + id + '_' + v);
str_3 = str_3.replace(/([a-z_-]+)\d+_\d/,'$1' + id + '_' + v);
DEMO
Your pattern actually includes the first digits, but it will store only the textual part into $1:
foo1_2
([a-z_-]+)\d+ = foo1
$1 = foo
The pattern stops searching at the first digits of the string.
if you want to replace any characters after the textual part, you could use this pattern:
/([a-z_-]+)\d+.*/
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
telephone number format with jquery®ex
i need to verify and convert any input val into telephone number format, i.e
input er+f375g25123435s67 i need to convert into +375 25 1234567
a most suitable code is:
$('input').live({
keyup: function(){
ipt = $(this).val().replace(/[^\d]*/g, "");
// remove non-digits
ipt = "+" + ipt.substring(0, 3) + " " + ipt.substring(4, 6) + " " + ipt.substring(7, 14);
$(this).val(ipt);
}
});
but i can't enter numbers after +375
1) how to enable numbers after +375
2) how to convert ipt.substring(0, 3) + " " + ipt.substring(4, 6) + " " + ipt.substring(7, 14) into regular expression?
HERE'S AN ANSWER: http://jsfiddle.net/5UvJr/
You may possibly want to look at this: http://digitalbush.com/projects/masked-input-plugin/
The substring indexes are wrong, try this:
ipt = "+" + ipt.substring(0, 3) + " " + ipt.substring(3, 5) + " " + ipt.substring(5, 12);
here is an answer: http://jsfiddle.net/5UvJr/
$('input').live({
keyup: function(){
var phone = $(this).val().replace(/\D/g, '');
phone = phone.substring(0,12);
var myRegexp = /(\d{3})(\d{2})(\d*)/g
var mphone = myRegexp.exec(phone);
$(this).val('+' + mphone [1] + ' ' + mphone [2] + ' ' + mphone [3]);
}
});