How to validate composed strings with regex [duplicate] - javascript

This question already has answers here:
Check whether a string matches a regex in JS
(13 answers)
Closed 4 months ago.
I want to validate/write a regex of this form: uuid OR uuid-cust-uuid
It should ONLY return true when I test with a valid uuid OR a composed uuid like uuid-cust-uuid
Here is the regex I have written thus far:
const uuid =
/[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}(\-cust\-[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12})?/;

You can use the test method and it will do the job.
const regexUUID = /[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}(\-cust\-[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12})?/;
const uuid = 'ec3bf3c6-85be-4169-971c-0c49be945b51';
console.log(regexUUID.test(uuid));
Edited:
As for your requirement, you can try something like this:
// Wrtie base uuid regex
const baseUUIDRegex = '[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}';
// Then use it inside another regex like this
const customRegex = `^${baseUUIDRegex}-cust-${baseUUIDRegex}$`;
console.log('ec3bf3c6-85be-4169-971c-0c49be945b51-cust-ec3bf3c6-85be-4169-971c-0c49be945b51'.match(customRegex));
Hope it will be helpful for you.

Related

Split the string between the two characters? [duplicate]

This question already has answers here:
RegEx to match stuff between parentheses
(4 answers)
Closed 6 months ago.
I had the following string ,
He is #(role)
I need to get the string which is present between #( and ).
Expected result ,
role
We can use match() here:
var input = "He is #(role)";
var role = input.match(/#\((.*?)\)/)[1];
console.log(role);
You have to use the split method of string which split the string where you want, answer of the question here:
const string = 'He is #(role)';
const answer = string.split('#');
if you console.log(answer) then the console show
['He is ', '(role)'];
const arrMatch = 'He is #(role)'.match(/\#\(([^\)]+)/)
const text = arrMatch[1]
console.log(text)
here is the best and simple way to do this with string slice method which helps you to splice the exact string which you want.
Here is the answer
const string = 'He is #(role)';
const answer = string.slice(8, 12);
console.log(answer);
Now you can see the result 'role'
Explain: here is the resource which helps you learn this method
https://www.w3schools.com/jsref/jsref_slice_string.asp#:~:text=The%20slice()%20method%20extracts,of%20the%20string%20to%20extract.

Replace values from an array in string non case sensitive in javascript [duplicate]

This question already has answers here:
Case insensitive replace all
(7 answers)
Closed 2 years ago.
My code is as follows:
array.forEach(el => {
string = string.replace(el, `censored`);
});
array : my array of words that I want to censor.
string : the string that the words need censoring.
My issue is that this process is quite slow and also if the word in my string is written using capitals, it's getting missed.
Any ideas how should I solve this issue?
Thank you.
maybe you can use regex
let array = ['mate']
let string = 'Hello Mate, how are you mate?'
let re = new RegExp(array.join("|"),"gi");
let str = string.replace(re, 'censored');
output:
"Hello censored, how are you censored?"

How to specify url from array with regex in js [duplicate]

This question already has an answer here:
Reference - What does this regex mean?
(1 answer)
Closed 2 years ago.
How can detect url's from this string. Urls are in quotes that cause problem with multiple items.
"{"output":["www.google.com"],"screenshots":["http://10.200.200.14:5000/screenshots/id=215585/1.png","http://10.200.200.14:5000/screenshots/id=215585/2.png"]}"
I need to extract below:
http://10.244.224.44:5000/screenshots/id=215585/1.png
http://10.244.224.44:5000/screenshots/id=215585/2.png
Edit: I edited the line, it is actually a string and I need to extract urls to make them clickable in ace editor. So Ace editor wants me to specify a regex pattern.
const CustomHighlightRules = function CustomHighlightRules() {
let rules = new HighlightRules().getRules();
for (const rule in rules) {
rules[rule].unshift({
token: ['clickables'],
regex: /(((https?:\/\/)|(www\.))[^\s]+)/,
});
Actually you don't need Regex here:
var objJSON = JSON.parse('{"output":["www.google.com"],"screenshots":["http://10.200.200.14:5000/screenshots/id=215585/1.png","http://10.200.200.14:5000/screenshots/id=215585/2.png"]}');
Will parse the Json in obj and then:
document.write(obj.screenshots);
Use obj.screenshots

How to dynamically combine two regex? [duplicate]

This question already has answers here:
Combining regular expressions in Javascript
(6 answers)
Combine Regexp?
(6 answers)
Closed 3 years ago.
Can two regex be combined? Like it should match this regex or the other. Ideally exclusively (xor).
For instance, I want to validate a phone number against a landline phone number regex and a mobile phone number regex.
I wish I could do something like this but it doesn't work:
const landlinePhoneRegExp = /(^1300\d{6}$)|(^1800|1900|1902\d{6}$)|(^0[2|3|7|8]{1}[0-9]{8}$)|(^13\d{4}$)|(^04\d{2,3}\d{6}$)/
const mobilePhoneRegExp = /^04[0-9 ]+/
const stripOutDelimiters = regex => etc...
const phoneRegExp = `/${stripOutDelimiters(landlinePhoneRegExp)}|${stripOutDelimiters(mobilePhoneRegExp)}/`,
UPDATE: I forgot to add that I'm using the Yup library for validation! The code looks like this:
const validationSchema = (t, i18n) => Yup.object.shape({
phone: Yup.string()
.required(t('formValidationPhoneRequired'))
.matches(localeRegex[i18n.language].phoneRegExp, t('formValidationPhoneInvalid'))
})
This explains why I was trying to dynamically combine the two regex into one like in the non-working example above.
I've been looking at the docs for a while now but there doesn't seem to be a way to do that. Maybe lazy() would be useful but apparently I can't use string.matches() then... unless I match (landlineMatch || mobileMatch) to boolean(), but how could I do that?
phone: Yup.lazy((value) => {
const landlineMatch = value.match(localeRegex[i18n.language].landlinePhoneRegExp)
const mobileMatch = value.match(localeRegex[i18n.language].mobilePhoneRegExp)
return Yup.string()
.required(t('formValidationPhoneRequired'))
.matches( ??? , t('formValidationPhoneInvalid'))
})
You're almost done, you just need to test if they match.
To test if a string matches, just use String.prototype.match():
landlineMatch = str.match(landlinePhoneRegExp)
mobileMatch = str.match(mobilePhoneRegExp)
There's no shortcut for the logical XOR test, you'll just have to use a combination of && and || like so:
(landlineMatch || mobileMatch) && !(landlineMatch && mobileMatch)

How to create regular expression in a loop? [duplicate]

This question already has answers here:
Javascript Regex: How to put a variable inside a regular expression? [duplicate]
(9 answers)
Closed 4 years ago.
I currently have a regex that looks like:
const ignoreRegex = new RegExp(/^\/(?!fonts|static).*$/)
However, I also have a dynamic array of strings like "test" which need to be ignored too. I need to somehow map through this array and add each string to the regex, such that:
const ignoreRegex = new RegExp(/^\/(?!fonts|static + ignoreRoutes.map(x => `|${x}`) + ).*$/)
How do I do this?
You can omit the / / surrounding your regular expression and use a string in the RegExp constructor.
See the code below.
const ignoreFolders = ["fonts", "static"];
const ignoreRoutes = ["route1", "route2"];
const ignore = ignoreFolders.concat(ignoreRoutes);
const ignoreRegex = new RegExp(`^\/(?!${ignore.join("|")}).*$`);
console.log(ignoreRegex);
If you have any regex special characters in your string, they will be escaped automatically.
const ignoreRoutes = ["fonts","static","aaa","bbb","ccc"];
const ignoreRegex = new RegExp(`^\\/(?!${ignoreRoutes.join("|")}).*$`);

Categories