Below is a very simple regex code, which works correctly in php and ruby, but not in JS. Plead help me get it working:
var r = /:[a-z]+/
var s = '/a/:b/c/:d'
var m = r.exec(s)
// now m is [":b"]
// it should be [":b", ":d"]
// because that's what i get in ruby and php
Using RegExp.exec() with g (global) modifier is meant to be used inside a loop for getting all matches.
var str = '/a/:b/c/:d'
var re = /:[a-z]+/g
var matches;
while (matches = re.exec(str)) {
// In array form, match is now your next match..
}
You can also use the String.match() method here.
var s = '/a/:b/c/:d',
m = s.match(/:[a-z]+/g);
console.log(m); //=> [ ':b', ':d' ]
var r = /:[a-z]+/g; // i put the g tag here because it needs to match all occurrences
var s = '/a/:b/c/:d';
var m = s.match(r);
console.log(m); // [':b',':d']
I used match because it returns all the matches in an array where as with exec you would have to loop through like the other examples.
Related
I am looking for an alternative for this:
(?<=\.\d\d)\d
(Match third digit after a period.)
I'm aware I can solve it by using other methods, but I have to use a regular expression and more importantly I have to use replace on the string, without adding a callback.
Turn the lookbehind in a consuming pattern and use a capturing group:
And use it as shown below:
var s = "some string.005";
var rx = /\.\d\d(\d)/;
var m = s.match(/\.\d\d(\d)/);
if (m) {
console.log(m[1]);
}
Or, to get all matches:
const s = "some string.005 some string.006";
const rx = /\.\d\d(\d)/g;
let result = [], m;
while (m = rx.exec(s)) {
result.push(m[1]);
}
console.log( result );
An example with matchAll:
const result = Array.from(s.matchAll(rx), x=>x[1]);
EDIT:
To remove the 3 from the str.123 using your current specifications, use the same capturing approach: capture what you need and restore the captured text in the result using the $n backreference(s) in the replacement pattern, and just match what you need to remove.
var s = "str.123";
var rx = /(\.\d\d)\d/;
var res = s.replace(rx, "$1");
console.log(res);
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 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 need to match all entries like { * } for string (using Javascript). How can I do it?
Here is an input: "#SD#{date};{time};{lat1};{lat2};{lon1};{lon2};{speed};{course};{height};{sats}\r\n";
thanks in advance
Using regular expression maybe:
var r = /{.*?}/g;
var s = "#SD#{date};{time};{lat1};{lat2};{lon1};{lon2};{speed};{course};{height};{sats}\r\n";
var matches = s.match(r);
Or if you want to strip those {} in results, you can run an .exec() loop to get a captured data only:
var r = /{(.*?)}/g;
var s = "#SD#{date};{time};{lat1};{lat2};{lon1};{lon2};{speed};{course};{height};{sats}\r\n";
var matches = [];
var match = null;
while(match = r.exec(s)) {
matches.push(match[1]);
}
You can try with the following regular expression:
var str = "#SD#{date};{time};{lat1};{lat2};{lon1};{lon2};{speed};{course};{height};{sats}\r\n".
var m = str.match(/{.*?}/g);
You'll find all the matches inside m.
Further references: http://www.w3schools.com/jsref/jsref_match.asp
For just the text within the brackets, you should be able to use this pattern:
var pattern = new RegExp("([^{|^}]+)(?=})", "g");
var testString = "#SD#{date};{time};{lat1};{lat2};{lon1};{lon2};{speed};{course};{height};{sats}\r\n";
var bracketTextArray = testString.match(pattern);
The bracketTextArray variable will be an array that contains the following values:
"date", "time", "lat1", "lat2", "lon1", "lon2", "speed", "course", "height", "sats"
The regex matches every occurrence of one or more of any character except { and } (that's this part: ([^{|^}]+)), that are immediately followed by a } character (that's this part: (?=})). The "g" in the RegExp definition makes the pattern "greedy", so that it will find all occurrences.
i have a string like this .
var url="http://localhost/elephanti2/chaink/stores/stores_ajax_page/5/b.BusinessName/asc/1/11"
i want to get substrings
http://localhost/elephanti2/chaink/stores/stores_ajax_page
and
5/b.BusinessName/asc/1/11
i want to split string from the 7 th slash and make the two sub-strings
how to do this ??,
i looked for split()
but in this case if i use it i have to con-cat the sub-strings and make what i want . is there a easy way ??
try this one:
var url="http://localhost/elephanti2/chaink/stores/stores_ajax_page/5/b.BusinessName/asc/1/11";
var parts = url.split('/');
var p1 = parts.slice(0,6).join('/');
var p2 = parts.slice(7).join('/');
alert(p1);
alert(p2);
p1 should get the first part and p2 is the second part
You can try this regex. Generally if your url pattern always follow this structure, it will work.
var pattern = /(\w+:\/\/(\w+\/){5})/i;
var url = "http://localhost/elephanti2/chaink/stores/stores_ajax_page/5/b.BusinessName/asc/1/11";
var result = url.split(pattern);
alert(result[1]);
alert(result[3]);
Try this :
var str = 'http://localhost/elephanti2/chaink/stores/stores_ajax_page/5/b.BusinessName/asc/1/11',
delimiter = '/',
start = 7,
tokens = str.split(delimiter).slice(start),
result = tokens.join(delimiter);
var match = str.match(/([^\/]*\/){5}/)[0];
Find this fiddle