I have the following code:
https://jsfiddle.net/s3fdjyjv/1
var re = /11\B/g;
var str = '11111vjknvkjdnfvk11kjdnkjfgbnkfgjbnk1111jkngknfbkjf11111111gbnf';
console.log(str.match(re));
I am trying to get only the first set of consecutive matches.
So, in this example I just want to get the first consecutive matches of 11, which should result in the first 1111.
How can I get this result?
The /11\B/g regex matches multiple 11 substrings that are followed with an alphanumeric character or an underscore, as \B is a non-word boundary.
I am trying to get only the first set of consecutive matches.
For that, you need a capturing group and a backreference:
var re = /(11)\1+/;
or
var re = new RegExp("(11)\1+");
Note the /g global modifier must be removed since you only need the first match.
var re = new RegExp("(11)\\1+");
var str = '11111vjknvkjdnfvk11kjdnkjfgbnkfgjbnk1111jkngknfbkjf11111111gbnf';
var m = str.match(re);
var res = m ? m[0] + ", at " + re.lastIndex : "";
document.body.innerHTML = res;
Related
So I have this (example) string: 1234VAR239582358X
And I want to get what's in between VAR and X. I can easily replace it using .replace(/VAR.*X/, "replacement");
But, how would I get the /VAR.*X/as a variable?
I think what you are looking for might be
string.match(/VAR(.*)X/)[1]
The brackets around the .* mark a group. Those groups are returned inside the Array that match creates :)
If you want to only replace what's in between "VAR" and "X" it would be
string.replace(/VAR(.*)X/, "VAR" + "replacement" + "X");
Or more generic:
string.replace(/(VAR).*(X)/, "$1replacement$2");
You can try use the RegExp class, new RegExp(`${VAR}.*X`)
You can store it as variable like this,
const pattern = "VAR.*X";
const reg = new RegExp(pattern);
Then use,
.replace(reg, "replacement");
If you
want to get what's in between VAR and X
then using .* would do the job for the given example string.
But note that is will match until the end of the string, and then backtrack to the first occurrence of X it can match, being the last occurrence of the X char in the string and possible match too much.
If you want to match only the digits, you can match 1+ digits in a capture group using VAR(\d+)X
const regex = /VAR(\d+)X/;
const str = "1234VAR239582358X";
const m = str.match(regex);
if (m) {
let myVariable = m[1];
console.log(myVariable);
}
Or you can match until the first occurrence of an X char using a negated character class VAR([^\r\nX]+)X
const regex = /VAR([^\r\nX]+)X/;
const str = "1234VAR239582358X";
const m = str.match(regex);
if (m) {
let myVariable = m[1];
console.log(myVariable);
}
var str = "lala";
var newStr = str.replace('l', 'm');
The value of newStr becomes 'mala', as the replace method finds the first occurrence of character in the string and replaces the character and then stops.
But I want the output "lama".
How can I achieve it?
You can use regex for this:
var str = "lala";
var newStr = str.replace(/l([^l]*)$/, 'm$1'); // lama
console.log(newStr);
This pattern matches an l followed by any number of characters that are not l until the end of the string. This will only match one time since the string ends only once (i.e in "lalblc" it matches "lc"). Then it replaces "lc" with "m" followed by the group of letters after the l (which is "c"). In the end, you are left with the original string but with the last l replaced with m.
[^l] means "any letter that is not l"
* means "any number of times (0 or more)"
The parenthesis create a capturing group which can be referenced using $1 in the replacement.
If you will be doing this frequently, it would be useful to move this to a function. You can make a function, replaceLast that can be called on strings by doing:
String.prototype.replaceLast = function (search, replace) {
return this.replace(new RegExp(search+"([^"+search+"]*)$"), replace+"$1");
}
str = "lala";
newStr = str.replaceLast("l", "m");
console.log(newStr);
You can match everything up to an "l" followed by anything that's not an "l":
var str = "lala";
var newStr = str.replace(/(.*)l([^l]*)$/, "$1m$2");
console.log(newStr);
The first group, (.*), will consume as much of the string as it can. The second group, ([^l]*)$, will match the rest of the source string after the last "l".
Here i've created a custom function also i've avoided using any regex since it's quite difficult for any beginner to understand.
var str = "lala";
const customReplace = (replaceChar, replaceWith, str) => {
const lastIndex = str.lastIndexOf(replaceChar);
const leftPortion = str.slice(lastIndex);
const rightPortion = str.slice(lastIndex+1);
return `${leftPortion}${replaceWith}${rightPortion}`;
}
console.log(customReplace('l', 'm', str))
You can use reverse, replace and reverse again.
You could take a search for l which is not followed by optional non l characters and an l.
var str = "lala",
newStr = str.replace(/l(?![^l]*l)/, 'm');
console.log(newStr);
or you can use Look ahead in RegEx to find the last character :
var str = "lala";
var newStr = str.replace(/l(?!.*l)/, 'm');
console.log(newStr);
for more information you can read this link
Here is a straightforward way to replace, a bit silly but it works as well
var str = "lalalc";
var newStr = [...str];
newStr[str.lastIndexOf('l')] ='m';
newStr.join('');
You can use this Regex to replace second occurance of letter:
var str = "lala";
var newStr = str.replace(/(?<=l.*?)l/,"m");
console.log(newStr);
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
I have string in this format:
var a="input_[2][invoiceNO]";
I want to extract "invoiceNo" string. I've tried:
var a="input_[2][invoiceNO]";
var patt = new RegExp('\[(.*?)\]');
var res = patt.exec(a);
However, I get the following output:
Array [ "[2]", "2" ]
I want to extract only invoiceNo from the string.
Note: Input start can be any string and in place of number 2 it can be any number.
I would check if the [...] before the necessary [InvoiceNo] contains digits and is preceded with _ with this regex:
/_\[\d+\]\s*\[([^\]]+)\]/g
Explanation:
_ - Match underscore
\[\d+\] - Match [1234]-like substring
\s* - Optional spaces
\[([^\]]+)\] - The [some_invoice_123]-like substring
You can even use this regex to find invoice numbers inside larger texts.
The value is in capture group 1 (see m[1] below).
Sample code:
var re = /_\[\d+\]\s*\[([^\]]+)\]/g;
var str = 'input_[2][invoiceNO]';
while ((m = re.exec(str)) !== null) {
alert(m[1]);
}
You can use this regex:
/\[(\w{2,})\]/
and grab captured group #1 from resulting array of String.match function.
var str = 'input_[2][invoiceNO]'
var m = str.match(/\[(\w{2,})\]/);
//=> ["[invoiceNO]", "invoiceNO"]
PS: You can also use negative lookahead to grab same string:
var m = str.match(/\[(\w+)\](?!\[)/);
var a="input_[2][invoiceNO]";
var patt = new RegExp('\[(.*?)\]$');
var res = patt.exec(a);
Try this:
var a="input_[2][invoiceNO]";
var patt = new RegExp(/\]\[(.*)\]/);
var res = patt.exec(a)[1];
console.log(res);
Output:
invoiceNO
You could use something like so: \[([^[]+)\]$. This will extract the content within the last set of brackets. Example available here.
Use the greediness of .*
var a="input_[2][invoiceNO]";
var patt = new RegExp('.*\[(.*?)\]');
var res = patt.exec(a);
How is it possible to match more than one string with regular expressions?
Here I want to match both name and txt, but only name is matched?
var reg = new RegExp('%([a-z]+)%', "g");
reg.exec('%name% some text %txt%');
You need to use String.match instead of exec:
'%name% some text %txt%'.match(reg);
Use match instead:
'%name% %txt%'.match(reg); //["%name%", "%txt%"]
exec only retrieves the first match (albeit with capturing groups).
If the capturing groups are important to you, you can use a loop:
var matches = [];
var str = '%name% some text %txt%';
var reg = new RegExp('%([a-z]+)%', "g");
while (match = reg.exec(str)){
matches.push(match);
}
If you only want to keep the captured groups, use this instead:
matches.push(match[1]);
The g flag does work but needs to be executed on the same string multiple times
var reg = new RegExp('%([a-z]+)%', "g");
var str = '%name% some text %txt%';
var result;
while( result = reg.exec( str ) ) { // returns array of current match
console.log( result[1] ); // index 0 is matched expression. Thereafter matched groups.
}
The above outputs name & txt to the console.
Example here