Regex not working properly in Javascript code - javascript

I have a JavaScript function that fires successfully on the onkeypress/onkeyup event for an asp.net textbox control as follows:
<asp:TextBox ID="txtboxLatestTag" runat="server" onkeypress="validate()" onkeyup="validate()"></asp:TextBox>
function validate() {
var str = $("#txtboxLatestTag").val();
var pattern = /^\d{1,2}[.]\d{1,2}[.]\d{1,2}[.]\d{1,2}/gm
if (!str.match(pattern))
{
document.getElementById("txtboxLatestTag").style.color = "red";
}
else
{
document.getElementById("txtboxLatestTag").style.color = "white";
}
The regex is supposed to match entries in the format of:
10.10.10.10 or
1.1.1.1
or anything allowing 1 to 2 digits between each "." character.
This works, however the problem is that it ALSO matches with
1.1.1.100 i.e. it should not allow 3 numbers at the end of the string, only 2.
This works perfectly in regexr.com but I cannot figure out why it is matching on this.
Thank you

I believe what you want to do to exclude extra characters at the end of the string is add in the end of input character $ (or end-of-line character, since you're using multiline mode). This will cause extra characters at the end to invalidate the match. For example:
var oldPattern = /^\d{1,2}[.]\d{1,2}[.]\d{1,2}[.]\d{1,2}/gm;
console.log("Old pattern match:");
console.log("10.10.10.100".match(oldPattern));
var pattern = /^\d{1,2}[.]\d{1,2}[.]\d{1,2}[.]\d{1,2}$/gm;
console.log("New pattern match:");
console.log("10.10.10.100".match(pattern));
console.log("10.10.10.1".match(pattern));

Related

Using JS to modify user input for REGEXP search

I'm taking user input from a searchbar and modifying it to a regexp. From there I can search a json file for valid values and return them. It works fine with input without quotes, but with them, I'm appending "\Q" and "\E" so I can find the entirety of the string (with spaces and other special characters).
if (searchField.includes('"')){
var tempexpress = searchField.substring(1,searchField.length-1);
var tempexpress = "\\Q" + tempexpress + "\\E";
var expression = new RegExp(tempexpress);
} else {
var tempexpress = searchField.replace('(',"\\(");
var tempexpress = tempexpress.replace(')',"\\)");
var tempexpress = tempexpress.replace(/'/g,"\\'");
var tempexpress = tempexpress.replace('*',"\.");
var expression = new RegExp(tempexpress, "i");
};
if (value.data.label.search(expression) != -1){
console.log('found it');
}
If I input "QTT6" into the search field (with quotes for a literal), then it creates the following regexp: /\QQTT6\E/
In my testing, I found that it doesn't match to QTT6 for some reason and I'm not sure why. Any help is appreciated.
Also I'm very new to JS and Jquery, so sorry if my code isn't very well put together.
Per Kelly's comment:
In JS you need to use ^ and $ instead of \Q and \E.
For more information, see the MDN docs on Regex Assertions:
^:
Matches the beginning of input. If the multiline flag is set to true, also matches immediately after a line break character. For example, /^A/ does not match the "A" in "an A", but does match the first "A" in "An A".
Note: This character has a different meaning when it appears at the start of a character class.
$:
Matches the end of input. If the multiline flag is set to true, also matches immediately before a line break character. For example, /t$/ does not match the "t" in "eater", but does match it in "eat".

Replce repeating set of character from end of string using regex

I want to remove all <br> from the end of this string. Currently I am doing this (in javascript) -
const value = "this is an event. <br><br><br><br>"
let description = String(value);
while (description.endsWith('<br>')) {
description = description.replace(/<br>$/, '');
}
But I want to do it without using while loop, by only using some regex with replace. Is there a way?
To identify the end of the string in RegEx, you can use the special $ symbol to denote that.
To identify repeated characters or blocks of text containing certain characters, you can use + symbol.
In your case, the final regex is: (<br>)*$
This will remove 0 or more occurrence of <br> from the end of the line.
Example:
const value = "this is an event. <br><br><br><br>"
let description = String(value);
description.replace(/(<br>)*$/g, '');
You may try:
var value = "this is an event. <br><br><br><br>";
var output = value.replace(/(<.*?>)\1*$/, "");
console.log(output);
Here is the regex logic being used:
(<.*?>) match AND capture any HTML tag
\1* then match that same tag zero or more additional times
$ all tags occurring at the end of the string

How to create a regex that checks the string contains specific pattern in javascript?

I have a requirement where I need to traverse through the string and get the first occurrence of a specific pattern like as follows,
i am a new **point**
On the occurrence of two consecutive character it must return true.
I must *not* be returned or*
The above pattern must return false.I tried to create regex following few links but the string.match method always returns null.
My code,
var getFormat = function(event) {
var element = document.getElementById('editor');
var startIndex = element.selectionStart;
var selectedText = element.value.slice(startIndex);
var regex = new RegExp(/(\b(?:([*])(?!\2{2}))+\b)/)
var stringMatch = selectedText.match(regex);
console.log('stringMatch', stringMatch);
}
<html>
<body>
<textarea onclick='getFormat(event);' rows='10' cols='10' id='editor'></textarea>
</body>
</html>
As I am new to regex I couldn't figure out where I am wrong.Could anyone help me out with this one?
On the occurrence of two consecutive character it must return true.
If I'm understanding you correctly. You just want to check if a string contains two consecutive characters, no matter which character. Then It should be enough doing:
(.)\1
Live Demo
This is of course assuming that it's literally any character. As in two consecutive whitespaces also being a valid match.
If you just need to check if there's two stars after each other. Then you don't really need regex at all.
s = "i am a new **point**";
if (s.indexOf("**") != -1)
// it's a match
If it's because you need the beginning and end of the two stars.
begin = s.indexOf("**");
end = s.indexOf("**", begin + 1);
Which you with regex could do like this:
((.)\2)(.*?)\1
Live Demo

Regular Expression: Allow only characters a-z, A-Z

ExtJS 5.1
Let's say I have an example like that, I want user's name-surname so I don't want any numbers or special chars, I tried so many possibilities but couldn't make it:
var controller=this;
var refs = controller.getReferences();
var exp = '/^([^0-9]*)$/';
onButtonClick: function(button, e, eOpts) {
if(refs.nameSurname.value.match(exp)){
Ext.Msg.alert('ERROR', 'BlaBla');
}
}
With this code, I have no error when i enter a number to text field...
Thank you.
Assuming you need to actually match a string that has no digits...
You should not enclose the regex literal with single quotes, remove them. You do not need the capture group, you can remove ( and ).
Use
var exp = /^[^0-9]*$/;
Now, to check if a string matches a regex, you will be safer using a RegExp#test().
See the demo below:
var refs_nameSurname = "Som8ehere";
if(!(/^[^0-9]*$/.test(refs_nameSurname))){
console.log('ERROR');
}
However, you can reverse the logic, and show an error once a digit is found inside a string (simpler!):
var refs_nameSurname = "Somehere12";
if(/[0-9]/.test(refs_nameSurname)){
console.log('ERROR');
}

Regex to check a substring is having all numeric or not (in Java script)

I am using following code to check first four characters are alphabate or not.
var pattern = new RegExp('^[A-Z]{4}');
if (enteredID.match(pattern))
isValidAlphabates = true;
else {
isValidAlphabates = false;
This is working fine; Now I need to check the next 6 characters (of the entered text) need to be only numeric (0 to 9).
I ve the option to use substring or substr method to extract that part & use the regular experssion: ^[0-9]{6}.
But is there a better way to do it, without using the substring method here.
To clarify, the ^ means "at the start of the string". So you can combine your two regexes to say "start with four A-Z then have six 6 0-9."
var pattern = new RegExp('^[A-Z]{4}[0-9]{6}');
var pattern = new RegExp('^[A-Z]{4}[0-9]{6}');
var pattern = new RegExp('^[A-Z]{4}[0-9]{6}$');
I added $ that means that checked string must end there.
You can check the whole string at once
var pattern = new RegExp('^[A-Z]{4}[0-9]{6}');

Categories

Resources