In Javascript, get length of matching regular expression - javascript

In Javascript, how do I get the length of the regex match?
For example, if the string is
str = "/abc/hellothere/andmore/"
And the regexp is
reg = new RegExp('/abc/[^/]*/');
Then I want 16, the length of
/abc/hellothere/

Assuming you actually want your regex to match your sample input:
var str = '/abc/hellothere/andmore/';
var reg = new RegExp('/abc/[^/]*/');
var matches = str.match(reg);
if (matches && matches.length) {
console.log(matches[0].length);
}
The expected output should be 16.
Refer to String.prototype.match and RegExp.prototype.exec.

Related

Ignore character in regex

I want to ignore 0 in the regex below. Currently, the regex returns an array and splitting the characters into n digits. I want the regex to ignore character 0.
var n = 2
var str = '123045';
var regex2 = new RegExp(`.{1,${n}}`,'g');
var reg = str.match(regex2)
One way you could achieve this is by removing the 0 before you perform your match. This can be done by using .replace() like so:
const n = 2
const str = '123045';
const regex2 = new RegExp(`.{1,${n}}`, 'g');
const reg = str.replace(/0/g, '').match(regex2);
console.log(reg); // [‘12’, ‘34’, ‘5’]
To ignore leading zeros, you can match for 0 followed by n amount of digits for each element in your matched array (using .map()) and .replace() this with the remaining digits by capturing them in a group, and using the group as the replacement:
const n = 2
const str = '123045';
const regex2 = new RegExp(`.{1,${n}}`, 'g');
const reg = str.match(regex2).map(m => m.replace(/0(\d+)/g, '$1')).join('').match(regex2);
console.log(reg); // [‘12’, ‘30’, ‘45’]
Best way is to use replace,
But if you want to do it using regex try (?!0)[\d] It shall give you matches 1,2,3,4,5

Remove string between two variables

I have a string which has some data with a few special characters, Need to remove the data between the desired special char in JavaScript.
The special char would be obtained in a variable.
var desiredChar = "~0~";
And Imagine this to be the Input string:
~0~1|0|20170807|45|111.00|~0~~1~1|0|20170807|50|666.00|~1~~2~1|0|20170807|55|111.00|~2~
So I'm supposed to remove the text in bold.
The desired output is supposed to be-
~1~1|0|20170807|50|666.00|~1~~2~1|0|20170807|55|111.00|~2~
I've tried using "Replace" and "Regex", but as the desired character is being passed in a variable and keeps changing I'm facing difficulties.
You can create your own regex based on whatever the bounding character(s) are that contain the text you want removed, and then replace any text that matches that regex with a blank string "".
The JS below should work for your use case (and it should work for multiple occurrences as well):
var originalText = "~0~1|0|20170807|45|111.00|~0~~1~1|0|20170807|50|666.00|~1~~2~1|0|20170807|55|111.00|~2~";
var desiredChar = "~0~";
var customRegex = new RegExp(desiredChar + ".*?" + desiredChar, "gi");
var processedText = originalText.replace(customRegex, "");
console.log(processedText);
You can build your regex from the constructor with a string input.
var desiredChar = "~0~";
// use the g flag in your regex if you want to remove all substrings between desiredChar
var myRegex = new Regex(desiredChar + ".*" + desiredChar, 'ig');
var testString = "~0~1|0|20170807|45|111.00|~0~~1~1|0|20170807|50|666.00|~1~~2~1|0|20170807|55|111.00|~2~";
testString = testString.replace(myRegex, "");
Given input string you can use .indexOf(), .lastIndexOf() and .slice().
Note, OR character | passed to RegExp constructor should be escaped to avoid RegExp created by passing string interpreting | character as OR | within resulting RegExp passed to .replace().
var desiredChar = "~0~";
var str = "~0~1|0|20170807|45|111.00|~0~~1~1|0|20170807|50|666.00|~1~~2~1|0|20170807|55|111.00|~2~";
var not = str.slice(str.indexOf(desiredChar), str.lastIndexOf(desiredChar) + desiredChar.length);
// escape OR `|`
var res = str.replace(new RegExp(not.replace(/[|]/g, "\\|")), "");
console.log(res)
You can use the RegExp object:
var regexstring = "whatever";
var regexp = new RegExp(regexstring, "gi");
var str = "whateverTest";
var str2 = str.replace(regexp, "other");
document.write(str2);
Then you can construct regexstring in any way you want.
You can read more about it at http://www.regular-expressions.info/javascript.html

Regexp with .exec not working

I want to match 3 letters and 3 digits with regexp and exec. But I dont get any result. Any idea what is wrong? The code is:
var regnr = "This is the pattern to match: WBJ124";
var patt = new RegExp("^\b[a-zA-Z]{3}\d{3}\b*$");
var sequence = '';
var grps = patt.exec(regnr);
if(grps!=null){
sequence = grps[0];
}
sequence is empty, but I expect it to be WBJ124
Best Regards
You have few mistakes in your regex like using ^ and $ when you are matching a substring in a longer string. Also you are using RegExp object that accepts a string literal hence requires double escaping.
You can use:
var regnr = "This is the pattern to match: WBJ124";
var patt = /\b[a-zA-Z]{3}\d{3}\b/; // or new RegExp("\\b[a-zA-Z]{3}\\d{3}\\b")
var grps = patt.exec(regnr);

Matching Regular Expression for URLS in JavaScript Produces null

I have the following regular expression which I have validated:
"(http|ftp|https)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,#?^=%&:/~+#-]*[\w#?^=%&/~+#-])?"
I have the following Javascript code to find regular expressions:
var cTextVal = "This URL should match http://google.com";
var regEx = "(http|ftp|https)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,#?^=%&:/~+#-]*[\w#?^=%&/~+#-])?"
var matches = cTextVal.match(regEx);
alert(matches); // This produces null
How do I find the string that matches this regular expression in JavaScript?
Update Based on Comments:
This crashes my code:
var regEx = /(http|ftp|https)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,#?^=%&:/~+#-]*[\w#?^=%&/~+#-])?/g
This produces null:
var regEx = "/(http|ftp|https)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,#?^=%&:/~+#-]*[\w#?^=%&/~+#-])?/g"
Escape forward slashes before second capture group
var regEx = /(http|ftp|https):\/\/([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,#?^=%&:/~+#-]*[\w#?^=%&/~+#-])?/;
var cTextVal = "This URL should match http://google.com";
var matches = cTextVal.match(regEx).shift();
console.log(matches);

Display characters other than alphabets using reqular expression

I have tried to display characters other than alphabets in the particular string but it is displaying only the first char.
var myArray = /[^a-zA-Z]+/g.exec("cdAbb#2547dbsbz78678");
The reason it is only displaying the first character is because with using exec and the g modifier (global), this method is meant to be used in a loop for getting all sub matches.
var str = "cdAbb#2547dbsbz78678";
var re = /[^a-zA-Z]+/g;
var myArray;
while (myArray = re.exec(str)) {
console.log(myArray[0]);
}
Output
#2547
78678
If you were wanting to combine the matches you could use the following.
var str = "cdAbb#2547dbsbz78678",
res = str.match(/[\W\d]+/g).join('');
# => "#254778678"
Or do a replacement
str = str.replace(/[a-z]+/gi, '');
You can do:
"cdAbb#2547dbsbz78678".match(/[^a-zA-Z]+/g).join('');
//=> #254778678
RegExp.exec with g (global) modifier needs to run in loop to give you all the matches.

Categories

Resources