JavaScript ReverseMatch - javascript

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.

Related

Replace character before date match

I want to replace the underscore that precedes a date in a string e.g.
thequick_brown_20210813_fox
To:
thequick_brown_red_20210813_fox
I.e. replace that underscore with _red_
This captures the date part: (20\d{2})(\d{2})(\d{2})
And to replace I assume I can just use str.replace
But not sure how I can capture the underscore that precedes it.
You can try the following RegEx with Positive Lookahead:
/_(?=\d{8})/
Where:
_ matches the character _
(?=\d{8}) - Positive Lookahead
\d - matches a digit (equivalent to [0-9])
{8} - matches the previous token exactly 8 times
var str = 'thequick_brown_20210813_fox';
var patt = /_(?=\d{8})/;
str = str.replace(patt, '_red_');
console.log(str);
This works
And as bonus I have a super robust regex for dates
const str = 'thequick_brown_20210813_fox';
const re = /_(?=\d{4}(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01]))/;
const newStr = str.replace(re, '_red_');
console.log(newStr);
The regex is from here
This is what I came up with using the RegEx you provided.
let str = "thequick_brown_20210813_fox";
let newStr = "";
let regex = /(20\d{2})(\d{2})(\d{2})/;
let splits = str.split(regex);
newStr += splits[0] + "red_";
for(let i=1; i<splits.length; i++){
newStr += splits[i];
}
console.log(newStr);
I would use as a matching regex:
_(?=20[0-9]{6})
_ Matches underscore if ...
(?=20[0-9]{6}) This is a lookahead assertion that the following characters must be '20' followed by 6 digits.
Note that the above only matches the underscore when followed by '20' followed by an additional 6 digits. So we simply replace the underscore with '_red_':
let s = 'thequick_brown_20210813_fox';
s = s.replace(/_(?=20[0-9]{6})/g, '_red_');
console.log(s);

Javascript regex to always find a match from the end?

I have a string which looks like below
str = "hey there = pola"
Now I need to check if there is equal = sign and the first word to the left of it. So this is what I do
str.match(/\w+(?= *=)/)[0]
So I get the desired result
But say I have a string like this
str = "hey there= pola so = boba"
Now I have two = signs. But the above regex will only give me the result for the first = sign.
Is there any regex that can always look for the first instance of = from the end of the string?
You can assert what is on the right is an equals sign followed by matching any char except an equals sign until the end of the string
\w+(?= *=[^=]*$)
In parts:
\w+
(?= Positive lookahead
*= Match 0+ occurrences of a space followed by =
[^=]* Match 0+ occurrences of = ( Use [^=\r\n]* to not cross line breaks)
$ End of string
) Close lookahead
Regex demo
const regex = /\w+(?= *=[^=]*$)/;
const str = `hey there= pola so = boba`;
console.log(str.match(regex)[0]);
Without using a lookahead, you could use a capturing group:
^.*\b(\w+) *=[^=]*$
Regex demo
const regex = /^.*\b(\w+) *=[^=]*$/m;
const str = `hey there= pola so = boba`;
console.log(str.match(regex)[1]);
I'm not much expert on regex but for you requirement I think split and pop should work
let str = "hey there= pola so = boba";
let endres = str.split('=').pop(); // gives the last element in the split array
Hope this helps.

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);

Recursively patten js

I want to check a recursively text that verufy three rules.
1º: All the string should be a sequence of numbers between 0-31 + a dot .
Example: 1.23.5.12
2º: The string can't begin or end with a dot.
Like this.
.1.23.5.12.
3º You can write a max of 51 digits (following the previous rules)
I tried to make a pattern to my js function. But this dont work.
This is my function:
var str = document.getElementById("numero").value;
var patt1 = /^[0-9]+\./g;
var result = str.match(patt1);
document.getElementById("demo").innerHTML = result;
What is wrong in the pattern?
You may use
/^(?!(?:\D*\d){52})(?:[12]?\d|3[01])(?:\.(?:[12]?\d|3[01]))*$/
See the regex demo
Details
^ - start of string
(?!(?:\D*\d){52}) - fail if there are 52 or more digits separated with any 0+ non-digits
(?:[12]?\d|3[01]) - 1 or 2 (optional) followed with any single digit or 3 followed with 0 or 1 (0 - 31)
(?:\.(?:[12]?\d|3[01]))* - zero or more consecutive repetitions of
\. - dot
(?:[12]?\d|3[01]) - see above (0 - 31)
$ - end of string.
Use it with test:
if (/^(?!(?:\D*\d){52})(?:[12]?\d|3[01])(?:\.(?:[12]?\d|3[01]))*$/.test(str)) {
// Valid!
}
Test:
var rx = /^(?!(?:\D*\d){52})(?:[12]?\d|3[01])(?:\.(?:[12]?\d|3[01]))*$/;
var strs = [".12", "123", "1.23.5.12", "12345678"];
for (var s of strs) {
console.log(s, "=>", rx.test(s));
}
The regex ^[0-9]+\. matches from the start of the string ^ one or more digits [0-9]+ followed by a dot \.
You might use:
^(?!(\.?\d){52})(?:[0-9]|[12][0-9]|3[01])(?:\.(?:[0-9]|[12][0-9]|3[01]))+$
Explanation
^ Assert the start of the line
(?!(\.?\d){52}) Negative lookahead to assert that what follows is not 52 times an optional dot followed by one or more digits
(?:[0-9]|[12][0-9]|3[01]) Match a number 0 - 31
(?:\.(?:[0-9]|[12][0-9]|3[01]))+ Repeat in a group matching a dot followed by a number 0 - 31 and repleat that one or more times so that a single digit wihtout a dot does not match
$ Assert the end of the string
const strings = [
'1.23.5.12',
'1.23.5.12.',
'.1.23.5.12.',
'1.23.5.12',
'1',
'1.23.5.12.1.23.5.1.23.5.12.1.23.5.1.23.5.12.1.23.5.1.23.5.12.1.23.5.1.23.5.12.1.23.5.2',
'1.23.5.12.1.23.5.12.1.23.5.12.1.23.5.12.1.23.5.12.1.23.5.12.1.23.5.12.1.23.5.12.1.23.5.12'
];
let pattern = /^(?!(\.?\d){52})(?:[0-9]|[12][0-9]|3[01])(?:\.(?:[0-9]|[12][0-9]|3[01]))+$/;
strings.forEach((s) => {
console.log(s + " ==> " + pattern.test(s));
});

js regex - checking number with optionally ending with /

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+(\/?)$/));

Categories