I have a string where I'm trying to grab the integer inside. The string looks like:
"(2) This is a string"
I need to grap that 2. but it could be any number so I tried:
var str = "(2) this is a string";
var patt = /\(\d\)/;
var num = str.match(patt);
This doesn't return the correct answer. Should I do a split on the () or is there a better regexp?
var str = "(2) this is a string";
var patt = /\((\d)\)/;
var num = str.match(patt)[1];
2 things. When you want to capture a segment form a matched string, you use () to note that. So I just wrapped the \d in parens to capture it.
Second, in order to access the captured segments, you must drill into the returned array. the match method will return an array where the first item is the entire matched string, and the second item is any matched capture groups. So use [1] to fetch the first capture group (second item in array)
Use this. doesnt matter how many parenthesis
var str = "(2) this is a string";
var patt = /\(\d\)/;
var num = str.match(patt)[0].replace("(", "").replace(")","")
This should work
var str = "(2) this is a string";
var a = /\([\d]*\)/g.exec(str)[0];
var num = a.substring(1, a.length-1);
var str = "(2) this is a string";
var patt = /\((\d+)\)/;
alert(str.match(patt)[1]);
This works!
Why it works. Because inside the (()) mayhem there's also a capture which populates the [1] elements in the matches array.
Related
I want to do this in node.js
example.js
var str = "a#universe.dev";
var n = str.includes("b#universe.dev");
console.log(n);
but with restriction, so it can search for that string only after the character in this example # so if the new search string would be c#universe.dev it would still find it as the same string and outputs true because it's same "domain" and what's before the character in this example everything before # would be ignored.
Hope someone can help, please
Look into String.prototype.endsWith: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
First, you need to get the end of the first string.
var ending = "#" + str.split("#").reverse()[0];
I split your string by the # character, so that something like "abc#def#ghi" becomes the array ["abc", "def", "ghi"]. I get the last match by reversing the array and grabbing the first element, but there are multiple ways of doing this. I add the separator character back to the beginning.
Then, check whether your new string ends the same:
var n = str.endsWith(ending);
console.log(n);
var str = "a#universe.dev";
var str2 = 'c#universe.dev';
str = str.split('#');
str2 = str2.split('#');
console.log(str[1] ===str2[1]);
With split you can split string based on the # character. and then check for the element on position 1, which will always be the string after #.
Declare the function
function stringIncludeAfterCharacter(s1, s2, c) {
return s1.substr(s1.indexOf(c)) === s2.substr(s2.indexOf(c));
}
then use it
console.log(stringIncludeAfterCharacter('a#universe.dev', 'b#universe.dev', '#' ));
var str = "a#universe.dev";
var n = str.includes(str.split('#')[1]);
console.log(n);
Another way !
var str = "a#universe.dev";
var n = str.indexOf(("b#universe.dev").split('#')[1]) > -1;
console.log(n);
I have this code, it looks alright and is really basic, but i can't make it work:
function checkValid(elem){
var abc = elem.value;
var re = "/[0-9]/";
var match = re.test(abc);
alert(match);
}
It matches 0 and 9, but not 1 to 8, what's wrong here? Thanks.
re is a string, not a RegExp object.
You need to use a regex literal instead of a string literal, like this:
var re = /[0-9]/;
Also, this will return true for any string that contains a number anywhere in the string.
You probably want to change it to
var re = /^[0-9]+$/;
Try removing the double quotes...
var re = /[0-9]/;
Use \d to match a number and make it a regular expresison, not a string:
var abc = elem.value;
var re = /\d/;
var match = re.test(abc);
alert(match);
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);
I have put this together getting help from other SO answers. With this I get ["__COL__", "COL"], what I want to get is ["COL", "COL_ID"]. What is the proper regex to use?
var myString = "this is a __COL__ and here is a __COL_ID__";
var myRegexp = /__([A-Z]+)__/g;
var match = myRegexp.exec(myString);
console.log(match); // ["__COL__", "COL"]
You are just including only uppercase alphabets, and missing the _. So, the RegEx becomes like this /__(\[A-Z_\]+)__/g. And exec function returns only the first match, so, we have to exec again and again till it returns null.
exec returns,
If the match succeeds, the exec method returns an array and updates
properties of the regular expression object. The returned array has
the matched text as the first item, and then one item for each
capturing parenthesis that matched containing the text that was
captured.
In our case, the first value would be the entire matched string, the second value would be the captured string. So, we are pushing only match[1] in the result.
var myString = "this is a __COL__ and here is a __COL_ID__";
var myRegexp = /__([A-Z_]+)__/g, match = myRegexp.exec(myString), result = [];
while (match) {
result.push(match[1]);
match = myRegexp.exec(myString);
}
console.log(result);
Output
[ 'COL', 'COL_ID' ]
This works (here's the jsfiddle):
var myString = "this is a __COL__ and here is a __COL_ID__";
var myRegexp = /([A-Z]+_[A-Z]+|[A-Z]+)(?=__)/g;
var match = myString.match(myRegexp);
console.log(match);
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