Suppose I have to access a some pattern of digit using javascript. Please have a look.
For Example :: Pattern needed :: Fomat - $12.00 only
If user enters the value 123.12 => Output = $123.12
If user enters the value 123.1 => Output = $123.10
If user enters the value 123.1237 => Output = $123.12 :: Here I am unable to get the first two element of second array having value as 1237.
Thanks
Why not:
var number = 123.1237;
var dollarAmount = number.toFixed(2);
console.log(dollarAmount);
Nasty string manipulation is not the answer here.
If you have '123.1237 as a string input, then input.split('.') would give you an array with two strings 123 and 1237. Thus what you really want to do is sub-string the second string to get the first two characters:
1237.subsring(0, 2);
Related
I am very new to making search text in array some elements in array are in rangers i.e it cant be anything after certain text in this AA and A regex and I have multi-dimensional array and I want search text in each array . So I wrote something like this.I put AA* in array so only first 2 character should match and A* for only one character match.
arr = [
["AA*","ABC","XYZ"] ,
["A*","AXY","AAJ"]
]
var text = "AA3";
for ($i=0; $i<arr.length; $i++ ){
var new_array = [];
new_array = arr[$i];
new_array.filter(function(array_element) {
var result = new RegExp(array_element).test(text);
if( result == true){
console.log(arr[$i]);
}
});
}
So what i want is when text = "AA3" or anything after double A AA[anything] and the output should be first array which is ["AA*","ABC","XYZ"] but I am getting both array as output and when text = "A3" then output should be second array which is ["A*","POI","LKJ"] but I am getting both array.But if text = "ABC" or text = "AAJ" then it should output first array or second array respectively.I dont know anything about how to write regex or is there anyway I can implement this using any other method.
Thanks in advance any advice will be helpful.
Summary
In short, the issue is "*"! The * found in the members of the set array is why you're getting the same array each time.
Detailed Info
Regexp is a one concept most developers find hard to understand (I am one of such btw 😅).
I'll start off with an excerpt intro to Regexp on MDN
Regexp are patterns used to match character combinations in strings - MDN
With that in mind you want to understand what goes on with your code.
When you create a Regex like /A*/ to test "AA3", what would be matched would be A, AA, etc. This is a truthy in javascript. You would want a more stricter matching with ^ or $ or strictly matching a number with \d.
I rewrote your code as a function below:
arr = [
["AA*", "ABC", "XYZ"],
["A*", "AXY", "AAJ"],
];
findInArray(arr, "AA3") // prints both array
findInArray(arr, "AAJ") // prints second array
findInArray(arr, "ABC") // prints first array
function findInArray(array, value) {
return array.filter((subArray) =>
subArray.some((item) => {
const check = new RegExp(value);
return check.test(item);
})
);
}
Problem
The problem lies in the fact you use each of the strings as a regex.
For a string with a * wildcard, this evaluates to zero or more matches of the immediately preceding item, which will always be true.
For a string consisting solely of alphanumerics, this is comparing a string to itself, which similarly will always give true.
For strings containing characters that constitute the regex's syntax definition, this could result in errors or unintended behavior.
MDN article on RegExp quantifiers
Rewrite
Assumptions:
The value with a * wildcard is always only at the 0th position,
There is only one such wildcard in its string,
The question mentions that for text = 'AAJ' only the 2nd array shall be returned, but both the AA* from the 1st array and AAJ from the 2nd would seem to match this text.
As such, I assume the wildcard can only stand for a number (as other examples seem to suggest).
Code:
const abc = (arrs, text) => {
return arrs.filter(arr => {
const regex = new RegExp(`^${arr[0].replace('*', '\\d+')}$`);
return regex.test(text) || arr.includes(text);
})
}
const arr = [
["AA*", "ABC", "XYZ"],
["A*", "AXY", "AAJ"]
];
console.log(
`1=[${abc(arr, "AA3")}]
2=[${abc(arr, "ABC")}]
3=[${abc(arr, "AAJ")}]`);
I want to make sure that the Form Textbox with ID input_1_4 has the right telephone format. To achieve this, every time a user enters a number on the textbox field, the script needs to eliminate the first zero that comes within the first 4 characters.
THIS IS MY JQUERY FUNCTION. What should I put to achieve my goal?
jQuery('#input_1_4').change(function() {
}
});
});
If the user enters +408765432, the script will remove zero because of it within the first 4 characters. The expected result must be +48765432.
If the user enters +4508765432, the result must be +458765432 because it is also within the first 4 characters.
However, if the user enters +4560876543 - The zero will not be removed because it is already the 5th character. The expected result is the same: +4560876543
Try this:
jQuery('#input_1_4').change(function() {
jQuery('#input_1_4').val(jQuery('#input_1_4').val().substring(0,4).replace("0", "")+jQuery('#input_1_4').val().substring(4))
}
});
});
Note: I do not use jQuery that much, nor do I know that this will even run without errors, but hopefully this can give you an idea of what to do:
1. Get the value of the form 2. Get the first four digits of the form (substring) 3. Replace all 0's with empty characters (use regex and replace) 4. Add the remaining digits back in and set the value of the text field.
Hope this helps!
you can try this
var myinput = "+40150544";
function removeit (input) {
var arr = input.split('');
arr.map((x,i)=> { i<4 && x==0 ? arr.splice(i,1) : x})
return arr.join('');
};
removeitit(myinput)
Perhaps the easiest thing would be to take a slice of the first four characters and replace the zero, then concat the rest of the string back together:
function removeZero(s) {
return s.slice(0,4).replace('0', '') + s.slice(4,)
}
let s1 = "+4560876543"
let s2 = "+408765432"
let s3 = "4508765432"
console.log(removeZero(s1))
console.log(removeZero(s2))
console.log(removeZero(s3))
// only removes the first zero
console.log(removeZero("4008765432"))
An alternative is to use a pure regex, thought this is a little harder to debug and read:
function removeZero(s) {
return s.replace(/(^[^0]{0,3})0/, '$1')
}
console.log("+4560876543 => ", removeZero('+4560876543'))
console.log("460876543 => ", removeZero('460876543'))
console.log("0460876543 => ", removeZero('0460876543'))
console.log("+40560876543 => ", removeZero('40560876543'))
But still dont understand : as in input box initially there is no data , however when the user starts typing the functions starts invoking the method in it , however the first line will [ $(this).val().split("-").join(""); ] will then look for the hyphen character to split into ... but as if the data typed by the user dosent contains any hyphens so what has to be replaced...??? like you explained above e.g. split("-") on "a-b-c" will give ["a","b","c"] ....this data already contains the hyphen character and which gets replaced with the character that we specify in brackets. Again at the other hand i dont understand this too : foo = foo.match(new RegExp('.{1,4}', 'g')).join("-"); , why there is single quotes in the RegExp, and what for the 1,4 stands for ..??? as far a i know that it must be meant for minimum 1 and maximum 4 charachters..? could you please help me understanding this..??? Appreciate your help
The function calls are evaluated from left to right. First val(), then split("-")and then join("").
What this does, is that it reads the value and since it seems to be a credit card number, the value will be something like 1234-5678-9012-3456.
The next thing is split the numbers at the hyphens with split("-"). This will result in a kind of list ['1234', '5678', '9012', '3456'].
This list is then joined using "" (Nothing actually) resulting in 1234567890123456, the number without the hyphens.
The same thing could be achieved with
$(this).val().replace(/-/g, "")
using Regular Expressions.
Hope this clarifies stuff!
$(this).val()
Gets the value of the element:
.split("-")
Build an array of strings that splits on '-' (hyphen). Basically, when you find '-' in the string, add it to i.e. 'foo-bar' becomes ['foo', 'bar'].
.join("");
Take the array and join each element back together with an empty string i.e. ['foo', 'bar'] becomes 'foobar'.
Split and join in one line
const result = "7.83".split('.').reduce((first, second) => `${first}' ${second}"`)
console.log(result)
7' 83"
I am trying to retrieve the first one or two letters from the outcode part of a postcode. The outcode can be in the format X1, XX11, XX1X, X1X. What I would like to do is to retrieve the bold part of these outcodes.
I am using a solution thus far which takes the first two characters of the string and then removes the numbers from the result:
PHP:
$str = preg_replace('/[0-9]+/', '', substr($outcode, 0, 2));
JavaScript:
outcode.substr(0, 2).replace(/\d+/g, '')
This works fine, yet I wonder if there is a more efficient way in PHP and JavaScript/jQuery, such as finding the first number in the string and removing it and everything else after it? I have about 3000 outcodes to filter and efficiency is key. Thanks.
EDIT:
Based on some comments, here are some real life examples, with desired results. Remember that the outcode string is only in one of the formats shown above, no other format:
EX13 => EX
EC2M => EC
E1W => E
E2 => E
This works well
"XX01XX".split(/[0-9]/)[0];
"XX".split(/[0-9]/)[0];
Add .slice(0,2) to get the first chars
In Javascript try:
firstDigit = outcode.match(/\d/); will give you the first digit in the string
index = outcode.indexOf(firstDigit);
outcode.substr(0, index);
I need to do a lot of regex things in javascript but am having some issues with the syntax and I can't seem to find a definitive resource on this.. for some reason when I do:
var tesst = "afskfsd33j"
var test = tesst.match(/a(.*)j/);
alert (test)
it shows
"afskfsd33j, fskfsd33"
I'm not sure why its giving this output of original and the matched string, I am wondering how I can get it to just give the match (essentially extracting the part I want from the original string)
Thanks for any advice
match returns an array.
The default string representation of an array in JavaScript is the elements of the array separated by commas. In this case the desired result is in the second element of the array:
var tesst = "afskfsd33j"
var test = tesst.match(/a(.*)j/);
alert (test[1]);
Each group defined by parenthesis () is captured during processing and each captured group content is pushed into result array in same order as groups within pattern starts. See more on http://www.regular-expressions.info/brackets.html and http://www.regular-expressions.info/refcapture.html (choose right language to see supported features)
var source = "afskfsd33j"
var result = source.match(/a(.*)j/);
result: ["afskfsd33j", "fskfsd33"]
The reason why you received this exact result is following:
First value in array is the first found string which confirms the entire pattern. So it should definitely start with "a" followed by any number of any characters and ends with first "j" char after starting "a".
Second value in array is captured group defined by parenthesis. In your case group contain entire pattern match without content defined outside parenthesis, so exactly "fskfsd33".
If you want to get rid of second value in array you may define pattern like this:
/a(?:.*)j/
where "?:" means that group of chars which match the content in parenthesis will not be part of resulting array.
Other options might be in this simple case to write pattern without any group because it is not necessary to use group at all:
/a.*j/
If you want to just check whether source text matches the pattern and does not care about which text it found than you may try:
var result = /a.*j/.test(source);
The result should return then only true|false values. For more info see http://www.javascriptkit.com/javatutors/re3.shtml
I think your problem is that the match method is returning an array. The 0th item in the array is the original string, the 1st thru nth items correspond to the 1st through nth matched parenthesised items. Your "alert()" call is showing the entire array.
Just get rid of the parenthesis and that will give you an array with one element and:
Change this line
var test = tesst.match(/a(.*)j/);
To this
var test = tesst.match(/a.*j/);
If you add parenthesis the match() function will find two match for you one for whole expression and one for the expression inside the parenthesis
Also according to developer.mozilla.org docs :
If you only want the first match found, you might want to use
RegExp.exec() instead.
You can use the below code:
RegExp(/a.*j/).exec("afskfsd33j")
I've just had the same problem.
You only get the text twice in your result if you include a match group (in brackets) and the 'g' (global) modifier.
The first item always is the first result, normally OK when using match(reg) on a short string, however when using a construct like:
while ((result = reg.exec(string)) !== null){
console.log(result);
}
the results are a little different.
Try the following code:
var regEx = new RegExp('([0-9]+ (cat|fish))','g'), sampleString="1 cat and 2 fish";
var result = sample_string.match(regEx);
console.log(JSON.stringify(result));
// ["1 cat","2 fish"]
var reg = new RegExp('[0-9]+ (cat|fish)','g'), sampleString="1 cat and 2 fish";
while ((result = reg.exec(sampleString)) !== null) {
console.dir(JSON.stringify(result))
};
// '["1 cat","cat"]'
// '["2 fish","fish"]'
var reg = new RegExp('([0-9]+ (cat|fish))','g'), sampleString="1 cat and 2 fish";
while ((result = reg.exec(sampleString)) !== null){
console.dir(JSON.stringify(result))
};
// '["1 cat","1 cat","cat"]'
// '["2 fish","2 fish","fish"]'
(tested on recent V8 - Chrome, Node.js)
The best answer is currently a comment which I can't upvote, so credit to #Mic.