JavaScript String test with array of RegEx - javascript

I have some doubts regarding RegEx in JavaScript as I am not good in RegEx.
I have a String and I want to compare it against some array of RegEx expressions.
First I tried for one RegEx and it's not working. I want to fix that also.
function check(str){
var regEx = new RegEx("(users)\/[\w|\W]*");
var result = regEx.test(str);
if(result){
//do something
}
}
It is not working properly.
If I pass users, it doesn't match. If I pass users/ or users/somestring, it is matching.
If I change the RegEx to (usersGroupList)[/\w|\W]*, then it is matching for any string that contains the string users
fdgdsfgguserslist/data
I want to match like if string is either users or it should contain users/something or users/
And also I want the string to compare it with similar regex array.
I want to compare the string str with users, users/something, list, list/something, anothermatch, anothermatch/something. If if it matches any of these expression i want to do something.
How can I do that?
Thanks

Then, you'll have to make the last group optional. You do that by capturing the /something part in a group and following it with ? which makes the previous token, here the captured group, optional.
var regEx = new RegExp("(users)(\/[\w|\W]*)?");

What about making:
the last group optional
starting from beginning of the string
Like this:
var regEx = new RegExp("^(users)(\/[\w|\W]*)?");
Same applies for all the others cases, e.g. for list:
var regEx = new RegExp("^(list)(\/[\w|\W]*)?");
All in One Approach
var regEx = new RegExp("^(users|list|anothermatch)(\/[\w|\W]*)?");
Even More Generic
var keyw = ["users", "list", "anothermatch"];
var keyws = keyw.join("|");
var regEx = new RegExp("^("+keyws+")(\/[\w|\W]*)?");

You haven't made the / optional. Try this instead
(users)\/?[\w|\W]*

Related

regex target specific character around variable

Hi,
I have this code:
var room = 'room2';
var exitroom = 'room1,room2,room3';
exitroom = exitroom.replace(/,${room},/,'');
console.log(exitroom);
you can try it here: https://jsfiddle.net/uq9w0Ls4/
my expected output is simply room1,room3 by taking room2 out but since it may change its position within the string I want to target the , no matter if it comes before or after the string but I cant figure out the regex logic here. I know I could just do simply:
var room = 'room2';
var exitroom = 'room1,room2,room3';
exitroom = exitroom.replace(room+',','').replace(','+room,'');
console.log(exitroom);
which works but I think regex would be a more direct approach.
Thank you.
First, by writing .replace(/,${room},/,'') you are not using the variable room.
To use a variable in a regex you should call new RegExp()
Second, if you want a regex that will match when the comma is before or after the word, you can use a group () with an Or | operator.
so it should look like this:
var reg = new RegExp(`(?:${room},|,${room})`, "g");
exitroom.replace(reg,'');
The ?: at the beginning of the group, is just so it should be a non-capturing group, it should work just fine also without it

Insert Character on String Javascript

Hi I want to insert additional character on strings from "replace" function.
example
string = "AGAS Ranges"
find = "gas"
my code
string.toLowerCase().replace("gas", `<b>${find}</b>`)
i want the result is like this, only add b and /b tag from the character you are looking for without changing the original words
"A<b>GAS</b> Ranges"
Thanks
The pattern can be a RegExp, so you can reference to first matched group like $1.
i modifier - makes the regex case insensitive.
console.log("AGAS Ranges".replace(/(gas)/i, "<b>$1</b>"))
Use a variable in a regular expression:
const string = 'AGAS Ranges';
const find = 'gas';
const regExp = new RegExp(`(${find})`, 'i');
console.log(string.replace(regExp, '<b>$1</b>'));

Extracting a complicated part of the string with plain Javascript

I have a following string:
Text
I want to extract from this string, with the use of JavaScript 'pl' or 'pl_company_com'
There are a few variables:
jan_kowalski is a name and surname it can change, and sometimes even have 3 elements
the country code (in this example 'pl') will change to other en / de / fr (this is that part of the string i want to get)
the rest of the string remains the same for every case (beginning + everything after starting with _company_com ...
Ps. I tried to do it with split, but my knowledge of JS is very basic and I cant get what i want, plase help
An alternative to Randy Casburn's solution using regex
let out = new URL('https://my.domain.com/personal/jan_kowalski_pl_company_com/Documents/Forms/All.aspx').href.match('.*_(.*_company_com)')[1];
console.log(out);
Or if you want to just get that string with those country codes you specified
let out = new URL('https://my.domain.com/personal/jan_kowalski_pl_company_com/Documents/Forms/All.aspx').href.match('.*_((en|de|fr|pl)_company_com)')[1];
console.log(out);
let out = new URL('https://my.domain.com/personal/jan_kowalski_pl_company_com/Documents/Forms/All.aspx').href.match('.*_((en|de|fr|pl)_company_com)')[1];
console.log(out);
A proof of concept that this solution also works for other combinations
let urls = [
new URL('https://my.domain.com/personal/jan_kowalski_pl_company_com/Documents/Forms/All.aspx'),
new URL('https://my.domain.com/personal/firstname_middlename_lastname_pl_company_com/Documents/Forms/All.aspx')
]
urls.forEach(url => console.log(url.href.match('.*_(en|de|fr|pl).*')[1]))
I have been very successful before with this kind of problems with regular expressions:
var string = 'Text';
var regExp = /([\w]{2})_company_com/;
find = string.match(regExp);
console.log(find); // array with found matches
console.log(find[1]); // first group of regexp = country code
First you got your given string. Second you have a regular expression, which is marked with two slashes at the beginning and at the end. A regular expression is mostly used for string searches (you can even replace complicated text in all major editors with it, which can be VERY useful).
In this case here it matches exactly two word characters [\w]{2} followed directly by _company_com (\w indicates a word character, the [] group all wanted character types, here only word characters, and the {}indicate the number of characters to be found). Now to find the wanted part string.match(regExp) has to be called to get all captured findings. It returns an array with the whole captured string followed by all capture groups within the regExp (which are denoted by ()). So in this case you get the country code with find[1], which is the first and only capture group of the regular expression.

Javascript RegEx contains

I'm using Javascript RegEx to compare if a string matches a standart format.
I have this variable called inputName, which has the following format (sample):
input[name='data[product][tool_team]']
And what I want to achieve with Javascript's regex is to determine if the string has the following but contains _team in between those brackets.
I tried the following:
var inputName = "input[name='data[product][tool_team]']";
var teamPattern = /\input[name='data[product][[_team]]']/g;
var matches = inputName.match(teamPattern);
console.log(matches);
I just get null with the result I gave as an example.
To be honest, RegEx isn't really my area, so I suppose it's wrong.
A couple of things:
You need to escape [ and ] as they have special meaning in regex
You need .* (or perhaps [^[]*) in front of _team if you want to allow anything there ([^[]* means "anything but a [ repeated zero or more times)
Example if you just want to know if it matches:
var string = "input[name='data[product][tool_team]']";
var teamPattern = /input\[name='data\[product\]\[[^[]*_team\]'\]/;
console.log(teamPattern.test(string));
Example if you need to capture the xyz_team bit:
var string = "input[name='data[product][tool_team]']";
var teamPattern = /input\[name='data\[product\]\[([^[]*_team)\]'\]/;
var match = string.match(teamPattern);
console.log(match ? match[1] : "no match");
If you are trying to check for DOM elements you can use attribute contains or attribute equals selector
document.querySelectorAll("input[name*='[_team]']")

Match a string between two other strings with regex in javascript

How can I use regex in javascript to match the phone number and only the phone number in the sample string below? The way I have it written below matches "PHONE=9878906756", I need it to only match "9878906756". I think this should be relatively simple, but I've tried putting negating like characters around "PHONE=" with no luck. I can get the phone number in its own group, but that doesn't help when assigning to the javascript var, which only cares what matches.
REGEX:
/PHONE=([^,]*)/g
DATA:
3={STATE=, SSN=, STREET2=, STREET1=, PHONE=9878906756,
MIDDLENAME=, FIRSTNAME=Dexter, POSTALCODE=, DATEOFBIRTH=19650802,
GENDER=0, CITY=, LASTNAME=Morgan
The way you're doing it is right, you just have to get the value of the capture group rather than the value of the whole match:
var result = str.match(/PHONE=([^,]*)/); // Or result = /PHONE=([^,]*)/.exec(str);
if (result) {
console.log(result[1]); // "9878906756"
}
In the array you get back from match, the first entry is the whole match, and then there are additional entries for each capture group.
You also don't need the g flag.
Just use dataAfterRegex.substring(6) to take out the first 6 characters (i.e.: the PHONE= part).
Try
var str = "3={STATE=, SSN=, STREET2=, STREET1=, PHONE=9878906756, MIDDLENAME=, FIRSTNAME=Dexter, POSTALCODE=, DATEOFBIRTH=19650802, GENDER=0, CITY=, LASTNAME=Morgan";
var ph = str.match(/PHONE\=\d+/)[0].slice(-10);
console.log(ph);

Categories

Resources