RegExp() logical and and or result unexpected [duplicate] - javascript

This question already has answers here:
Regular Expressions: Is there an AND operator?
(14 answers)
Closed 7 years ago.
I have a simple filter function in my javascript, based on an input box.
function filter(selector, query) {
query = $.trim(query); //trim white space
query = query.replace(/ /gi, '|'); //add OR for regex
$(selector).each(function() {
($(this).text().search(new RegExp(query, "i")) < 0) ? (do something here)
So, if I have a table with a list of words, eg.
Alpha Centauri,
Beta Carbonate,
Charly Brown,
...
and I enter 'alpha cen' into my input box, the function searches for ('alpha' or 'cen') and returns the one record as desired.
However, if I replace the '|' with a '&' to search for ('alpha' and 'cen') I get no results. Even if I enter 'alpha centauri', I get no result at all.
Why?

While a | in a regex allows alternation, an & carries no special meaning. Your current code is trying to find a literal match for alpha&cen, which clearly doesn't match any of your data.

Related

How to use RegEx in JavaScript replace function [duplicate]

This question already has an answer here:
javascript regexp replace not working, but string replace works
(1 answer)
Closed 1 year ago.
Hello team I am new to JS so I am trying to use RegEx with replacing to take input from the user and replace it if it doesn't match the RegEx I have to be able to put 7 digits or 6 digits followed with one letter currently I am doing this
someID.replace('^(([0-9]{1,7})|([0-9]{1,6}[a-zA-Z]{1}))$')
I am not able to replace the current string with the RegEx expression if I enter
12345678900 it remain the same in that situation I need to be 1234567 after the replace or if I have 12345678asd to be 123456a. How can I achieve that by only replace function and a RegEx expresion
You need to use a different regex and a dirrent replace function.
You will also need to get rid of $ if you want to be able to successfully match the string, without worrying about how it ends.
const sampleIDs = [
"123456789000",
"123456abc",
];
sampleIDs.forEach(id => {
const clean = id.match(/^\d{6}[\d\D]/);
console.log(clean[0]);
});

How to Replace Colon and Star Special Characters in JavaScript Regex [duplicate]

This question already has answers here:
Replace multiple characters in one replace call
(21 answers)
Closed 4 years ago.
I am trying to replace star (*) and colon (:) with an empty string ("") and the string can be as follows:
Either: Registration No: already exists*
OR: *Registration No: already exists
So, I don't want (*) as well as (:) and output should be Registration No already exists how can I solve it.
Trying as follows:
var txt = str.replace(/:\*/ig,"");
Please help me and thanks in advance
You regex matches :*. You could match either of them using a character class:
var txt = str.replace(/[:*]/g,"");
const strings = [
"Registration No: already exists*",
"*Registration No: already exists"
];
strings.forEach((s) => {
console.log(s.replace(/[:*]/g, ""));
});
Another way without using a character class is to use a pipe or alteration to separate each group. This however, requires that you escape special characters and this does allow for group matches instead of single character matches:
var txt = str.replace(/:|\*/ig, "");

How to check if a string meets required format using regex in javascript? [duplicate]

This question already has answers here:
Regex pattern accepting comma separated values
(5 answers)
Closed 4 years ago.
I want to check if a given string meets the required format in javascript. I want to use regex to do it, but I can not write the proper regex.
The required format is like optiona;optionb;optionc, and there will be
at least one ; in the string to separate the option, each option will
have at least three characters.
The options value can not contain ; but can contain empty space inside it (not in the beginning or end)
below is some example of it:
var str1="aaa;BBC;ccc";//valid
var str2=";aaa;bbb;ccc";//invalid, because it starts with ;
var str3="aaa;bbb;ccc;";//invalid, because it ends with ;
var str4="aaa;bbb;ccc;ddd"; //valid
var str5="aaa;b;ccc";//invalid, because the second option is b, the length is less than 3
var str5="aaa;bbb;;ccc";//invalid, because it has duplicate ;
var str6="aa a;bbb;ccc";//valid
var str7="aaa ;bbb;ccc";//invalid,empty space in the end of first option
var str8=" aaa;bbb;ccc";//invalid,empty space in the begin the first option
var str9="aaa;bb b;ccc;ddd";//valid
var str10="aaa;bbb ;ccc;ddd";//invalid,empty space in the end of second option
var11="aaa;bbb";//valid
How to use regex to check it. Can anyone help me? Thanks in advance!
The only tricky part to this problem is checking length while following other rules. So an option with 3 characters long would be matched with:
\w[ \w]+\w
Here is the regex:
^\w[ \w]+\w(;\w[ \w]+\w)+$
^^^^^^^^^^ ^^^^^^^^^^
Beginning and end of input string anchors, ^ and $, should be used. I used a capturing group construct but you may want to change it to a non-capturing one.
Live demo

Looking to trim a string using javascript / regex [duplicate]

This question already has an answer here:
Reference - What does this regex mean?
(1 answer)
Closed 4 years ago.
I'm looking for some assistance with JavaScript/Regex when trying to format a string of text.
I have the following IDs:
00A1234/A12
0A1234/A12
A1234/A12
000A1234/A12
I'm looking for a way that I can trim all of these down to 1234/A12. In essence, it should find the first letter from the left, and remove it and any preceding numbers so the final format should be 0000/A00 or 0000/AA00.
Is there an efficient way this can be acheived by Javascript? I'm looking at Regex at the moment.
Instead of focussing on what you want to strip, look at what you want to get:
/\d{4}\/[A-Z]{1,2}\d{2}/
var str = 'fdfhfjkqhfjAZEA0123/A45GHJqffhdlh';
match = str.match(/\d{4}\/[A-Z]{1,2}\d{2}/);
if (match) console.log(match[0]);
You could seach for leading digits and a following letter.
var data = ['00A1234/A12', '0A1234/A12', 'A1234/A12', '000A1234/A12'],
regex = /^\d*[a-z]/gi;
data.forEach(s => console.log(s.replace(regex, '')));
Or you could use String#slice for the last 8 characters.
var data = ['00A1234/A12', '0A1234/A12', 'A1234/A12', '000A1234/A12'];
data.forEach(s => console.log(s.slice(-8)));
You could use this function. Using regex find the first letter, then make a substring starting after that index.
function getCode(s){
var firstChar = s.match('[a-zA-Z]');
return s.substr(s.indexOf(firstChar)+1)
}
getCode("00A1234/A12");
getCode("0A1234/A12");
getCode("A1234/A12");
getCode("000A1234/A12");
A regex such as this will capture all of your examples, with a numbered capture group for the bit you're interested in
[0-9]*[A-Z]([0-9]{4}/[A-Z]{1,2}[0-9]{2})
var input = ["00A1234/A12","0A1234/A12","A1234/A12","000A1234/A12"];
var re = new RegExp("[0-9]*[A-Z]([0-9]{4}/[A-Z]{1,2}[0-9]{2})");
input.forEach(function(x){
console.log(re.exec(x)[1])
});

Removing any character besides 0-9 + - / * and ^ [duplicate]

This question already has answers here:
Replace method doesn't work
(4 answers)
Closed 4 years ago.
I'm trying to further my understanding of regular expressions in JavaScript.
So I have a form that allows a user to provide any string of characters. I'd like to take that string and remove any character that isn't a number, parenthesis, +, -, *, /, or ^. I'm trying to write a negating regex to grab anything that isn't valid and remove it. So far the code concerning this issue looks like this:
var pattern = /[^-\+\(\)\*\/\^0-9]*/g;
function validate (form) {
var string = form.input.value;
string.replace(pattern, '');
alert(string);
};
This regex works as intended on http://www.infobyip.com/regularexpressioncalculator.php regex tester, but always alerts with the exact string I supply without making any changes in the calculator. Any advice or pointers would be greatly appreciated.
The replace method doesn't modify the string. It creates a new string with the result of the replacement and returns it. You need to assign the result of the replacement back to the variable:
string = string.replace(pattern, '');

Categories