Searching keywords in JavaScript - javascript

Here's an example of the customer codes:
C000000123
C000000456
If I input C123 in the search box, "C000000123" will automatically display.
9 numbers are fixed.
Please help me, a short sample was shown to me but I don't get it.
function test(key, num, digit) {
let retStr;
xxxx (condition)
retun retStr;
}
here's an elaboration:
**
input:123
output:A00000123
input:1
output:A00000001
input:99999
output:A00099999
**
here's the detailed demand:
Since it takes time and effort to enter the management number “alphabet + numeric value 9 digits” on the search screen, when the alphabetic number and the number excluding the leading 0 are entered, it is automatically complemented so that it becomes 9 padded with zeros.
sorry i'm very very new to programming in javascript

Try this:
May be what you want...
Please test it and tell if its what you want.
function getOutput(input){
var str=input.substring(1,input.length);
var padd0=9-str.length;
var zr="000000000";
var zrsub=zr.substring(0,padd0);
var output=input[0]+zrsub+""+str;
return output;
}
//Example: Call it like (NB any letter can be used):
getOutput("C123"); //or
getOutput("D123");

You can use .endsWith in js which takes a string and a search string and returns true if the specified string ends with the search string.
This function takes an array of customer ids and a search string and returns the matching customer id
function searchCustomer(customers, searchString) {
return customers.find(customer => customer.endsWith(searchString));
}
searchCustomer(['C000000123', 'C000000456'], 123); // "C000000123"
searchCustomer(['C000000123', 'C000000456'], 456); // "C000000456"
searchCustomer(['C000000123', 'C000000456', 'A00000001'], 1); //"A00000001"

Related

How to make regular expression only accept special formula?

I'm making html page for special formula using angularJS.
<input ng-model="expression" type="text" ng-blur="checkFormula()" />
function checkFormula() {
let regex;
if (scope.formulaType === "sum") {
regex = "need sum regular expression here"; // input only like as 1, 2, 5:6, 8,9
} else {
regex = "need arithmetic regular expression here"; // input only like as 3 + 4 + 6 - 9
}
if (!regex.test(scope.expression)) {
// show notification error
Notification.error("Please input expression correctly");
return;
}
// success case
if (scope.formulaType === "sum") {
let fields = expression.split(',');
let result = fields.reduce((acc, cur) => { return acc + Number(cur) }, 0);
// processing result
} else {
// need to get fields with + and - sign.
// TODO: need coding more...
let result = 0;
// processing result
}
}
So I want to make inputbox only accept my formula.
Formulas are two cases.
1,2,3:7,9
or
4-3+1+5
First case, means sum(1,2,3,4,5,6,7,9) and second case means (4-3+1+5).
But I don't know regular expression how to process it.
I searched google, but I didn't get result for my case.
So I want to need 2 regex match.
1,2,3:7,9
Fot this pattern, you can try this one:
^\d+(?::\d+)?(?:,\d+(?::\d+)?)*$
^\d+(?::\d+)?
matches string starts with a number(e.g. 1) or two numbers separated by a column (e.g. 1:2)
(?:,\d+(?::\d+)?)*$
repeats the previous pattern with a comma in front of it as many time as possible until meets the end of the string (e.g. ,2:3,4:5,6)
4-3+1+5
Fot this pattern, you can try this one:
^\d+(?:[+-]\d+)*$
Like the previous one, this is much simpler
^\d+
starts with a number(e.g. 12)
(?:[+-]\d+)*$
repeats the previous pattern with a - or + in front of it as many time as possible until meets the end of the string (e.g. +2-3+14)
Also, if you need at least one pair of numbers.
Such as 1,2 is allowed but just 1 is not. You can just change the * before $ to +:
^\d+(?::\d+)?(?:,\d+(?::\d+)?)+$
^\d+(?:[+-]\d+)+$
And if you allow white spaces in between them:
^\d+(?:\s*:\s*\d+)?(?:\s*,\s*\d+(?:\s*:\s*\d+)?)+$
^\d+(?:\s*[+-]\s*\d+)+$

JavaScript regex: capturing optional groups while having a strict matching

I am trying to extract some data from user input that should follow this format: 1d 5h 30m, which means the user is entering an amount of time of 1 day, 5 hours and 30 minutes.
I am trying to extract the value of each part of the input. However, each group is optional, meaning that 2h 20m is a valid input.
I am trying to be flexible in the input (in the sense that not all parts need to be input) but at the same time I don't watch my regex to match some random imput like asdfasdf20m. This one should be rejected (no match).
So first I am getting rid of any separator the user might have used (their input can look like 4h, 10m and that's ok):
input = input.replace(/[\s.,;_|#-]+/g, '');
Then I am capturing each part, which I indicate as optional using ?:
var match = /^((\d+)d)?((\d+)h)?((\d+)m)?$/.exec(input);
It is kind of messy capturing an entire group including the letter when I only want the actual value, but I cannot say that cluster is optional without wrapping it with parentheses right?
Then, when an empty group is captured its value in match is undefined. Is there any function to default undefined values to a particular value? For example, 0 would be handy here.
An example where input is "4d, 20h, 55m", and the match result is:
["4d20h55m", "4d", "4", "20h", "20", "55m", "55", index: 0, input: "4d20h55m"]
My main issues are:
How can I indicate a group as optional but avoid capturing it?
How can I deal with input that can potentially match, like abcdefg6d8m?
How can I deal with an altered order? For example, the user could input 20m 10h.
When I'm asking "how to deal with x" I mean I'd like to be able to reject those matches.
As variant:
HTML:
<input type="text">
<button>Check</button>
<div id="res"></div>
JS:
var r = [];
document.querySelector('button').addEventListener('click', function(){
var v = document.querySelector('input').value;
v.replace(/(\d+d)|(\d+h)|(\d+m)/ig, replacer);
document.querySelector('#res').innerText = r;
}, false);
function trim(s, mask) {
while (~mask.indexOf(s[0])) {
s = s.slice(1);
}
while (~mask.indexOf(s[s.length - 1])) {
s = s.slice(0, -1);
}
return s;
}
function replacer(str){
if(/d$/gi.test(str)){
r[0] = str;
}
else if(/h$/gi.test(str)){
r[1] = str;
}
else if(/m$/gi.test(str)){
r[2] = str;
}
return trim(r.join(', '), ',');
}
See here.

Obtain numbers from a field and process them

I have a field which obtains it input through a list of links associated with numbers. (Similar to a calculator but without operators). I want to retrieve these numbers and put them through a function which divides them by 12. (A conversion from feet to inches).
First I have a list of jQuery click functions like this:
$('#a0').click(function(){
writeInput(input, one); // var one = 1;
});
Next I have the function "write Input" (This is where the numbers are displayed on a "screen")
function writeInput(field, str){
$input = $(field);
var text = $input.val($input.val() + str);
$input.text(text);
convert(text);
}
And lastly I have a function which is supposed to divide the number inputted by 12
function convert(input){
var divide = (input / 12);
$("#output").html(divide); //output is a paragraph where the number is displayed
}
When I run my code I am getting NAN output where the number should be. I have tried parseInt() and other tricks. But the closest I have come to something correct is when I got [object] [object] output.
Any help would be appreciated. Thanks!
In your code text is a jQuery object, you are using val as setter which returns a jQuery object, you should use val/text method as a getter for retrieving updated value.
function writeInput(field, str){
var text = $(field).val(function(i, v){
return v + str;
}).text(function(i, t){
return t + str
}).val();
convert(text);
}

How to append an extra 'Zero' after decimal in Javascript

Hye,
Iam new to javascript working with one textbox validation for decimal numbers . Example format should be 66,00 .but if user type 66,0 and dont type two zero after comma then after leaving text box it should automatically append to it .so that it would be correct format of it . How can i get this .How can i append ?? here is my code snippet.
function check2(sender){
var error = false;
var regex = '^[0-9][0-9],[0-9][0-9]$';
var v = $(sender).val();
var index = v.indexOf(',');
var characterToTest = v.charAt(index + 1);
var nextCharAfterComma = v.charAt(index + 2);
if (characterToTest == '0') {
//here need to add
}
}
Use .toFixed(2)
Read this article: http://www.javascriptkit.com/javatutors/formatnumber.shtml
|EDIT| This will also fix the issue if a user types in too many decimals. Better to do it this way, rather than having a if to check each digit after the comma.
.toFixed() converts a number to string and if you try to convert it to a float like 10.00
then it is impossible.
Example-
10.toFixed(2) // "10.00" string
parseFloat("10.00") // 10
Number("10.00") // 10

How to achieve String Manipulation in JavaScript

The problem statement is like this: I have a contract. On renewal on every month the contract name should append with renewal identifier. For example at beginning the name is myContract then on first renewal name should be myContract-R1, next renewal name should be myContract-R2 and so on.. On each renewal, the name should automatically change. So in Jquery how can I do this?
This is a JavaScript question, not a jQuery question. jQuery adds little to JavaScript's built-in string manipulation.
It sounds like you want to take a string in the form "myContract" or "myContract-Rx" and have a function that appends "-R1" (if there's no "-Rx" already) or increments the number that's there.
There's no shortcut for that, you have to do it. Here's a sketch that works, I expect it could be optimized:
function incrementContract(name) {
var match = /^(.*)-R([0-9]+)$/.exec(name);
if (match) {
// Increment previous revision number
name = match[1] + "-R" + (parseInt(match[2], 10) + 1);
}
else {
// No previous revision number
name += "-R1";
}
return name;
}
Live copy
You can use a regular expression for this:
s = s.replace(/(-R\d+)?$/, function(m) {
return '-R' + (m.length === 0 ? 1 : parseInt(m.substr(2), 10) + 1);
});
The pattern (-R\d+)?$ will match the revision number (-R\d+) if there is one (?), and the end of the string ($).
The replacement will return -R1 if there was no revision number before, otherwise it will parse the revision number and increment it.
how you get renewal number? Calculating from date, or getting from database?
var renewal = 1,
name = 'myContract',
newname = name+'R'+renewal;
or maybe like
$(function(){
function renew(contract){
var num_re = /\d+/,
num = contract.match(num_re);
if (num==null) {
return contract+'-R1';
} else {
return contract.replace(num_re,++num[0]);
}
}
var str = 'myContract';
new_contract = renew(str); // myContract-1
new_contract = renew(new_contract); // myContract-2
new_contract = renew(new_contract); // myContract-3
});
Here jQuery can't help you. It's pure JavaScript working with strings
P.S. I have here simple reg exp, that's not concrete for your example (but it works). Better use reg-exp from example of T.J. Crowder

Categories

Resources