js regex - checking number with optionally ending with / - javascript

I want to check if the url is either in the pattern that:
end with digits:
www.example.com/projects/123
or possibly end with digits and /:
www.example.com/projects/123/
which I don't know if user is going to add in the / at the end of the url.
What I have currently is:
var lastPart = window.location.pathname.substr(window.location.pathname.lastIndexOf('/')+1);
lastPart.match(/\d$/);
this will return true if it end with digits. if I do:
lastPart.match(/\d\/$/);
this will return true if it end with digits with / at the end. However, we cannot be sure if the user will put in the / or not.
So, How can we write the regex which end with digits and optionally / at the end?

You may use a ? quantifier after /:
/\d+\/?$/
See the regex demo.
Details
\d+ - 1+ digits
\/? - 1 or 0 occurrences of /
$ - end of string.
JS demo:
var strs = ['www.example.com/projects/123', 'www.example.com/projects/123/', 'www.example.com/projects/abc'];
var rx = /\d+\/?$/;
for (var s of strs) {
console.log(s, '=>', rx.test(s));
}

You could do it like this and make the / optional ?:
\d+\/?$
Explanation
Match one or more digits \d+
Match an optional forward slash \/?
Assert the end of the string $
var strings = [
"www.example.com/projects/123",
"www.example.com/projects/123/"
];
for (var i = 0; i < strings.length; i++) {
console.log(/\d+\/?$/.test(strings[i]));
}

Try
/\d+(\/?)$/
Explanation
\d+ will match one or more digits
(\/?) will match zero or one /
$ asserts end of string
For example
window.location.pathname.match( /\d+(\/?)$/ )
Demo
var regex = /\d+(\/?)$/;
var str1 = "www.example.com/projects/123";
var str2 = "www.example.com/projects/123/";
var badStr ="www.example.com/projects/as";
console.log( !!str1.match( regex ) );
console.log( !!str2.match( regex ) );
console.log( !!badStr.match( regex ) );

var string = 'www.example.com/projects/123/';
console.log(string.match(/\d+(\/?)$/));
var string = 'www.example.com/projects/123';
console.log(string.match(/\d+(\/?)$/));

Related

Regex to get substring between first and last occurence

Assume there is the string
just/the/path/to/file.txt
I need to get the part between the first and the last slash: the/path/to
I came up with this regex: /^(.*?).([^\/]*)$/, but this gives me everything in front of the last slash.
Don't use [^/]*, since that won't match anything that contains a slash. Just use .* to match anything:
/(.*?)\/(.*)\/(.*)/
Group 1 = just, Group 2 = the/path/to and Group 3 = file.txt.
The regex should be \/(.*)\/. You can check my below demo:
const regex = /\/(.*)\//;
const str = `just/the/path/to/file.txt`;
let m;
if ((m = regex.exec(str)) !== null) {
console.log(m[1]);
}
This regex expression will do the trick
const str = "/the/path/to/the/peace";
console.log(str.replace(/[^\/]*\/(.*)\/[^\/]*/, "$1"));
[^\/]*\/(.*)\/[^\/]*
If you are interested in only matching consecutive parts with a single / and no //
^[^/]*\/((?:[^\/]+\/)*[^\/]+)\/[^\/]*$
^ Start of string
[^/]*\/ Negated character class, optionally match any char except / and then match the first /
( Capture group 1
(?:[^\/]+\/)* Optionally repeat matching 1+ times any char except / followed by matching the /
[^\/]+ Match 1+ times any char except /
) Close group 1
\/[^\/]* Match the last / followed by optionally matching any char except /
$ End of string
Regex demo
const regex = /^[^/]*\/((?:[^\/]+\/)*[^\/]+)\/[^\/]*$/;
[
"just/the/path/to/file.txt",
"just/the/path",
"/just/",
"just/the/path/to/",
"just/the//path/test",
"just//",
].forEach(str => {
const m = str.match(regex);
if (m) {
console.log(m[1])
};
});

JavaScript ReverseMatch

Is simple, i have this sentence:
str = "aeiou";
Need RegExp to scan string every X chars, but in reverse.
Example:
let every=2,
match = new RegExp(/>>RegExp Here<</gi);
//result "a ei ou"
Use
let str = "Hello world, 13th Mar 2020.";
let every=2;
let rx = new RegExp(`(?=(?:[^]{${every}})+$)`, 'g');
console.log(str.replace(rx, "_"));
// => H_el_lo_ w_or_ld_, _13_th_ M_ar_ 2_02_0.
The regex is /(?=(?:[^]{2})+$)/g, see the regex demo. It matches any location in the string that is followed with one or more repetitions of any two chars up to the string end, and inserts _ at that location.
Details
(?= - start of a positive lookahead:
(?:[^]{2}) - any char ([^] = [\s\S]), 1 or more times (thanks to +)
$ - end of string
) - end of the lookahead.

Javascript string match specific regex

I want to match specific string from this variable.
var string = '150-50-30-20=50+skip50-20-10-5=15+1*2*3*4=24+50-50*30*20=0+skip2*4*8=64';
Here is my regex :
var string = '150-50-30-20=50+skip50-20-10-5=15+1*2*3*4=24+50-50*30*20=0+skip2*4*8=64';
var match_data = [];
match_data = string.match(/[0-9]+(?:((\s*\-\s*|\s*\*\s*)[0-9]+)*)\s*\=\s*[0-9]+(?:(\s*\+\s*[0-9]+(?:((\s*\-\s*|\s*\*\s*)[0-9]+)*)\s*=\s*[0-9]+)*)/g);
console.log(match_data);
The output will show
[
0: "150-50-30-20=50"
1: "50-20-10-5=15+1*2*3*4=24+50-50*30*20=0"
2: "2*4*8=64"
]
The result that I want to match from string variable is only
[
0: "150-50-30-20=50"
1: "1*2*3*4=24"
2: "50-50*30*20=0"
]
You may use ((?:\+|^)skip)? capturing group before (\d+(?:\s*[-*\/+]\s*\d+)*\s*=\s*\d+) in the pattern, find each match, and whenever Group 1 is not undefined, skip (or omit) that match, else, grab Group 2 value.
var string = '150-50-30-20=50+skip50-20-10-5=15+1*2*3*4=24+50-50*30*20=0+skip2*4*8=64',
reg = /((?:^|\+)skip)?(\d+(?:\s*[-*\/+]\s*\d+)*\s*=\s*\d+)/gi,
match_data = [],
m;
while(m=reg.exec(string)) {
if (!m[1]) {
match_data.push(m[2]);
}
}
console.log(match_data);
Note that I added / and + operators ([-*\/+]) to the pattern.
Regex details
((?:^|\+)skip)? - Group 1 (optional): 1 or 0 occurrences of +skip or skip at the start of a string
(\d+(?:\s*[-*\/+]\s*\d+)*\s*=\s*\d+) - Group 2:
\d+ - 1+ digits
(?:\s*[-*\/+]\s*\d+)* - zero or more repetitions of
\s*[-*\/+]\s* - -, *, /, + enclosed with 0+ whitespaces
\d+ - 1+ digits
\s*=\s* - = enclosed with 0+ whitespaces
\d+ - 1+ digits.
As per your input string and the expected results in array, you can just split your string with + and then filter out strings starting with skip and get your intended matches in your array.
const s = '150-50-30-20=50+skip50-20-10-5=15+1*2*3*4=24+50-50*30*20=0+skip2*4*8=64'
console.log(s.split(/\+/).filter(x => !x.startsWith("skip")))
There are other similar approaches using regex that I can suggest, but the approach mentioned above using split seems simple and good enough.
try
var t = string.split('+skip');
var tt= t[1].split('+');
var r = [t[0],tt[1],tt[2]]
var string = '150-50-30-20=50+skip50-20-10-5=15+1*2*3*4=24+50-50*30*20=0+skip2*4*8=64';
var t = string.split('+skip');
var tt= t[1].split('+');
var r = [t[0],tt[1],tt[2]]
console.log(r)
const string = '150-50-30-20=50+skip50-20-10-5=15+1*2*3*4=24+50-50*30*20=0+skip2*4*8=64';
const stepOne = string.replace(/skip[^=]*=\d+./g, "")
const stepTwo = stepOne.replace(/\+$/, "")
const result = stepTwo.split("+")
console.log(result)

Javascript Regex: Capture between two asterisks with multiple asterisks in comma delimited string

I am trying to capture all characters between multiple instances of asterisks, which are comma delimited in a string. Here's an example of the string:
checkboxID0*,*checkboxID1*,&checkboxID2&,*checkboxID3*,!checkboxID4!,checkboxID5*
The caveat is that the phrase must start and end with an asterisk. I have been able to come close by using the following regex, however, it won't discard any matches when the captured string is missing the starting asterisk(*):
let str = "checkboxID0*,*checkboxID1*,&checkboxID2&,*checkboxID3*,!checkboxID4!,checkboxID5*"
const regex = /[^\,\*]+(?=\*)/gi;
var a = str.match(regex)
console.log(a) // answer should exclude checkboxID0 and checkboxID5
The answer returns the following, however, "checkboxID0 and checkboxID5" should be excluded as it doesn't start with an asterisk.
[
"checkboxID0",
"checkboxID1",
"checkboxID3",
"checkboxID5"
]
Thanks, in advance!
You need to use asterisks on both ends of the pattern and capture all 1 or more chars other than commas and asterisks in between:
/\*([^,*]+)\*/g
See the regex demo
Pattern details
\* - an asterisk
([^,*]+) - Capturing group 1: one or more chars other than , and *
\* - an asterisk
JS demo:
var regex = /\*([^,*]+)\*/g;
var str = "checkboxID0*,*checkboxID1*,&checkboxID2&,*checkboxID3*,!checkboxID4!,checkboxID5*";
var m, res = [];
while (m = regex.exec(str)) {
res.push(m[1]);
}
console.log(res);

javascript match specific name plus / and characters after it

match a path for a specific word and a / and any characters that follow.
For example.
const str = 'cars/ford';
const isCars = str.match('cars');
What I want to do is make sure it matches cars and has a slash and characters after the / then return true or false.
The characters after cars/... will change so I can't match it excatly. Just need to match any characters along with the /
Would love to use regex not sure what it should be. Looking into how to achieve that via regex tutorials.
var str = "cars/ford";
var patt = new RegExp("^cars/"); //or var patt = /^cars\//
var res = patt.test(str); //true
console.log(res);
https://www.w3schools.com/js/js_regexp.asp
https://www.rexegg.com/regex-quickstart.html
You could use test() that returns true or false.
const str = "cars/ford";
const str2 = "cars/";
var isCars = (str)=>/^cars\/./i.test(str)
console.log(isCars(str));
console.log(isCars(str2));
Here is a quick regex to match "cars/" followed by any characters a-z.
(cars\/[a-z]+)
This will only match lowercase letters, so you can add the i flag to make it case insensitive.
/(cars\/[a-z]+)/i
It is a basic regular expression
var str = "cars/ford"
var result = str.match(/^cars\/(.*)$/)
console.log(result)
^ - start
cars - match exact characters
\/ - match /, the \ escapes it
(.*) - capture group, match anything
$ - end of line
Visualize it: RegExper

Categories