Regex exact text match is not working - javascript

I am trying to perform exact match of the text keyed in a textbox but, somehow it is working as partial match. I tried different options but could not figure out the cause.
RegExp.escape = function (text) {
//escape the +,[,?... characters
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}
var resultLbl = $('#ResultLbl');
$('#SearchTxtBox').bind('change keyup', function () {
resultLbl.text('');
var options = [];
options.push('[1]My]');
options.push('[2]My Name]');
options.push('[3]Name]');
options.push('[2]My Name]');
var searchStr = RegExp.escape($.trim($(this).val()));
var searchArr = [];
if (searchStr != '' && searchStr != null) {
searchStr = searchStr.replace(/\,/g, '\\ ')
searchArr = searchStr.split('\\ ');
}
var search = searchArr[0];
search = search.replace(/[.?*+^$[\]\\(){}|-]/g, '');
var regex = new RegExp($.trim(search), 'gi');
$.each(options, function (i, option) {
if (option.match(regex) !== null) {
resultLbl.append(option + ' ');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Search:
<input type="text" id="SearchTxtBox"/>
<br/>
<label id='ResultLbl'></label>
Expectation:
If you key in the text 'Name' in textbox, only '[3]Name' should be
matched.
If you key in the text 'My Name' in textbox, only '[2]My
Name' should be matched.
Any suggestions are appreciated.

Instead of complex pre-processing, you can just test if the string matches this pattern:
^\[\d+\]<searchStr>\]$
with
var regex = new RegExp("^\\[\\d+\\]" + $.trim(searchStr) + "\\]$", 'gi');
Here is an updated snippet:
RegExp.escape = function (text) {
//escape the +,[,?... characters
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}
var resultLbl = $('#ResultLbl');
$('#SearchTxtBox').bind('change keyup', function () {
resultLbl.text('');
var options = [];
options.push('[1]My]');
options.push('[2]My Name]');
options.push('[3]Name]');
options.push('[2]My Name]');
var searchStr = RegExp.escape($.trim($(this).val()));
var regex = new RegExp("^\\[\\d+\\]" + $.trim(searchStr) + "\\]$", 'gi');
$.each(options, function (i, option) {
if (option.match(regex) !== null) {
resultLbl.append(option + ' ');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Search:
<input type="text" id="SearchTxtBox"/>
<br/>
<label id='ResultLbl'></label>

Related

JavaScript regex.exec() should intended to use an assembled regEx

if I use ( https://jsfiddle.net/fgsvzn4a/ ) :
var text = "ui1pu";
var regExParameter = '\d+';
var regEx = '/(.*)' + regExParameter + '(.*)/gi';
var matches = regEx.exec(text);
if(matches && matches[1]) {
var str1 = matches[1];
var str2 = matches[2];
var newStr = str1 + str2
console.log(newStr);
}
i get this error:
Paused on exception
TypeError: regEx.exec is not a function
this prototype is working (inspired by https://stackoverflow.com/a/15845184/2891692 ):
var text = "my1bla";
var matches = /(my)\d+(.*)/gi.exec(text);
if(matches && matches[1]) {
var str1 = matches[1];
var str2 = matches[2];
var newStr = str1 + str2
alert(newStr);
}
but i want to use input parameters to build the regex (first example).
i get ReferenceError: Regex is not defined if i try this:
var text = "ui1pu";
var regExParameter = '\d+';
var regExString = '/(.*)' + regExParameter + '(.*)/gi';
var regEx = new Regex(regExString);
var matches = regEx.exec(text);
if(matches && matches[1]) {
var str1 = matches[1];
var str2 = matches[2];
var newStr = str1 + str2
console.log(newStr);
}
any idea?
Use the RegExp constructor. Note that the slashes should be omitted from the string and the flags should be passed as the second argument.
var text = "ui1pu";
var regExParameter = '\\d+';
var regExString = '(.*)' + regExParameter + '(.*)';
var regEx = new RegExp(regExString, 'gi');
var matches = regEx.exec(text);
if(matches && matches[1]) {
var str1 = matches[1];
var str2 = matches[2];
var newStr = str1 + str2
console.log(newStr);
}
Based on the previous correct answers, I was able to come up with this more comprehensive solution. Its a little modification of this correct answer by Unmitigated and all answers :
// window.replaceDOM = function (regExParameter, replaceParameter) {
function replaceDOM(regExParameter, replaceParameter) {
// let reg = '/' + search + '/';
// regExParameter = '\\d+';
console.log('regExParameter=' + regExParameter);
const regExString = '(\\w+)' + regExParameter + '(\\w+)'; // ugly but needet. that escape, that double backslash
console.log('regExString=' + regExString);
const regEx = new RegExp(regExString, 'gi');
let elems = document.body.getElementsByTagName("*");
for (i in elems) {
let ele = elems[i];
if(ele.classList){
const val = ele.classList.value;
if(!val)
continue;
const matches = regEx.exec(val);
if(matches && matches[1]) {
console.log('val=' + val);
const str1 = matches[1];
const str2 = matches[2];
const valNew = str1 + replaceParameter + str2
// alert(valNew);
console.log('valNew=' + valNew);
ele.classList.value = ele.classList.value.replace(val, valNew);
}
}
};
}
.my1bla {
background-color: black;
}
.mybla {
background-color: blue;
}
<button onclick="replaceDOM('y\\d+','y')">
change the style class from DIV using regEx</button>
<div class="my1bla">
I am a DIV element
</div>

Testing if a string starts and ends with a certain string with RegExp in javascript

I am testing this string "error code: 32603 error message: message here" with this regex:
RegExp(/^32603*/).test(string) returns false every time
I want it to match only that exact string. Meaning I don't want it to return true just because it has a 3 in the string.
If you wish to know that the string contains the number 32603 you can use:
RegExp(/\s32603\s/).test(string)
It will match any string that contains this exact number with spaces around it.
If you want to handle the case that the number appears at the start or at the end of the string, use:
RegExp(/\b32603\b/).test(string)
TRY IT:
<script>
try {
var util = {
startWith: function (source, search, ignoreCase) {
search = this.regExpEscapeSpecialCharacters(search);
var ignore = (ignoreCase) ? "gi" : "g";
var reg = new RegExp("^" + search + "", ignore);
return reg.test(source);
},
endWith: function (source, search, ignoreCase) {
search = this.regExpEscapeSpecialCharacters(search);
var ignore = (ignoreCase) ? "gi" : "g";
var reg = new RegExp(search + "$", ignore);
return reg.test(source);
},
contain: function (source, search, ignoreCase) {
search = this.regExpEscapeSpecialCharacters(search);
var ignore = (ignoreCase) ? "gi" : "g";
var reg = new RegExp(search, ignore);
return reg.test(source);
},
regExpEscapeSpecialCharacters: function (a) {
return a.toString().replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
},
};
//EXAMPLES:
var text = "hello world";
var search1 = "he";
var search2 = "ld";
if (util.startWith(text, search1, true) && util.endWith(text, search2, true)) {
alert("match");
}
} catch (e) {
alert(e);
}
</script>

Validate MAC Address onkeyup

I'm trying to validate a form field for MAC Addresses.
I've got this which works.
$('body').on('keyup', '#macAddess', function(e){
var e = $(this).val();
var r = /([a-f0-9]{2})([a-f0-9]{2})/i,
str = e.replace(/[^a-f0-9]/ig, "");
while (r.test(str)) {
str = str.replace(r, '$1' + ':' + '$2');
}
e = str.slice(0, 17);
$(this).val(e)
});
As the user is typing it's formatting the MAC Address, adding : after every pair of characters. It will only allow a-f and 0-9 so no invalid characters are being added.
I'd like to expand on it a little.. As the user is entering the MAC address I want a class adding to input showing it is wrong, until a fully formed MAC address is entered.
eg:
if (MAC is invalid) $('#' + id).addClass('badMac')
So if the user is entering a value the class will be added and only removed when a fully formed and valid mac is entered.
I'd like to keep in all with in the on('keyup') function.
How do I test if it is invalid and then set the class ?
You can test it with a regular expression that checks if the MAC address is valid:
var regexp = /^(([A-Fa-f0-9]{2}[:]){5}[A-Fa-f0-9]{2}[,]?)+$/i;
var mac_address = $(this).val();
if(regexp.test(mac_address)) {
//valid!
} else {
//invalid!
}
Note that if you write this on keyup event, you'll obtain the invalid statement till the user writes a whole valid MAC address.
Edit
Snippet working:
var regexp = /^(([A-Fa-f0-9]{2}[:]){5}[A-Fa-f0-9]{2}[,]?)+$/i;
var mac_address = "fa:09:91:d5:e4:5a";
if(regexp.test(mac_address)) {
console.log("Valid: "+ mac_address);
} else {
console.log("Invalid: "+ mac_address);
}
So try this code:
$('body').on('keyup', '#macAddess', function(e){
var e = $(this).val();
var r = /([a-f0-9]{2})([a-f0-9]{2})/i,
str = e.replace(/[^a-f0-9]/ig, "");
while (r.test(str)) {
str = str.replace(r, '$1' + ':' + '$2');
}
e = str.slice(0, 17);
$(this).val(e);
var regexp = /^(([A-Fa-f0-9]{2}[:]){5}[A-Fa-f0-9]{2}[,]?)+$/i;
var mac_address = $(this).val();
if(regexp.test(mac_address)) {
//valid!
} else {
//invalid!
}
});
function isValidMac(mystring){
var regex = /^([0-9A-F]{2}[:-]){5}([0-9A-F]{2})$/;
return regex.test(mystring);
}
$('body').on('keyup', '#macAddress', function(e){
var e = $(this).val();
var r = /([a-f0-9]{2})([a-f0-9]{2})/i,
str = e.replace(/[^a-f0-9]/ig, "");
while (r.test(str)) {
str = str.replace(r, '$1' + ':' + '$2');
}
e = str.slice(0, 17);
$(this).val(e)
$("#macAddress").toggleClass("badMac",!isValidMac(e));
});
input.badMac {
background-color : red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="macAddress">
I recommend you to use input event, which will also handle use cases when user uses Ctrl+C, Ctrl+V to input the MAC address, also together with the validation the code should look like this:
$(function() {
var regexp = /^(([A-Fa-f0-9]{2}[:]){5}[A-Fa-f0-9]{2}?)+$/i;
$("#macAddess").on("input", function(e) {
var tb = $(this);
var val = tb.val().replace(/[^a-f0-9]/ig, "");
var r = /([a-f0-9]{2})([a-f0-9]{2})/i;
while (r.test(val)) {
val = val.replace(r, '$1' + ':' + '$2');
}
val = val.slice(0, 17);
tb.val(val);
tb.toggleClass("badMac", !regexp.test(tb.val()));
});
});
.badMac {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="macAddess" />
You can use jQuery´s toggleClass() with a bool value. In this case with the return value of your regex test.
$('body').on('keyup', '#macAddess', function(e){
var input = $(this).val();
var regexp = /^(([A-Fa-f0-9]{2}[:]){5}[A-Fa-f0-9]{2}[,]?)+$/i;
$("#your-input-id").toggleClass("valid", regexp.test(input));
});

regex exact match in function

my function below searches a table, currently it searches for anything like, i want it to do an exact match, could you help me out?
Thanks
function searchTable(inputVal, tablename) {
var table = $(tablename);
table.find('tr:not(.header)').each(function (index, row) {
var allCells = $(row).find('td');
if (allCells.length > 0) {
var found = false;
allCells.each(function (index, td) {
var regExp = new RegExp(inputVal, 'i');
if (regExp.test($(td).text())) {
found = true;
return false;
}
});
if (found == true) $(row).show().removeClass('exclude'); else $(row).hide().addClass('exclude');
}
});
}
Your current Regex is case insensitive. An exact match would imply case sensitivity.
var regExp = new RegExp("^" + inputVal + "$", 'i'); // case insensitive
or
var regExp = new RegExp("^" + inputVal + "$"); // case sensitive

Parsing the url querystring using jquery and inserting the value in a textbox?

post.php?replyto=username&othervariable=value
For example, if I click a link with this url, then I want to take the replyto=username value and insert the value in a textbox using jquery.
function insertParamIntoField(url, param, field) {
var anchor = document.createElement('a'), query;
anchor.value = url;
query = anchor.query.split('&');
for(var i = 0, kv; i < query.length; i++) {
kv = query[i].split('=', 2);
if (kv[0] == param) {
field.value = kv[1];
return;
}
}
}
$("a .reply").click(function () {
insertParamIntoField(this.href, "replyto", $("input .inputField")[0]);
return false; // prevent default action
});
this is my html code:
<textarea name="inputField" id="inputField" tabindex="1" rows="2" cols="40"></textarea>
<a class ="reply" href="home.php?replyto=username">reply</a>
function insertParamIntoField(url, param, field) {
var anchor = document.createElement('a'), query;
anchor.href = url;
query = anchor.search.substring(1, anchor.search.length).split('&');
for(var i = 0, kv; i < query.length; i++) {
kv = query[i].split('=', 2); console.log(kv);
if (kv[0] == param) {
field.value = kv[1];
return;
}
}
}
$("a.reply").click(function () {
insertParamIntoField(this.href, "replyto", $("textarea.inputField")[0]);
return false; // prevent default action
});
The insertParamIntoField function will work for any well formed URL (as a string). It works by creating a new anchor DOMElement (but never attaches it to the dom) for that URL and then by using the built in properties of anchor elements (query, hash, etc.) to extract what we want.
If the URL is from an anchor element, we can create a new version of this function that uses that existing anchor rather than creating a new one:
function insertParamIntoField(anchor, param, field) {
var query = anchor.search.substring(1, anchor.search.length).split('&'); // anchor is a DOMElement
for(var i = 0, kv; i < query.length; i++) {
kv = query[i].split('=', 2);
if (kv[0] == param) {
field.value = kv[1];
return;
}
}
}
$("a.reply").click(function () {
insertParamIntoField(this, "replyto", $("textarea.inputField")[0]);
return false; // prevent default action
});
Parsing the URL can be done with a simple function. Use this in your Javascript:
$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
return results[1] || 0;
}
You can then call:
$.urlParam('username');
and it will return the user name. So, to actually use it with your text box, do:
$('#textBoxId').val($.urlParam('username'));
$('textarea').val("<?php echo $_GET['replyto']");
Using the code from this SO answer (which is great btw) by Artem Barger to get any parameter by name from the query string you could do:
function getParameterByName( name )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if(results == null )
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
Then just insert the value into the textbox:
$("#yourTextBox").val(getParameterByName('replyto'));
You should be able to grab the ?replyto=username&othervariable=value part with window.location.search, then you have to get the part you want
var print = '?replyto=username&othervariable=value'; // Would be window.location.search in practice
$('textBox').val(print.substr(print.indexOf('replyto=')+8,print.indexOf('&')-(print.indexOf('replyto=')+8)));
​
Here is some Javascript that should help you. Just take the return value from the getQuerystringNameValue() function and use $("#textboxID").val(returnValue); to assign it to the textbox.
alert("name1" + " = " + getQuerystringNameValue("name1"));
alert("name2" + " = " + getQuerystringNameValue("name2"));
alert("name3" + " = " + getQuerystringNameValue("name3"));
function getQuerystringNameValue(name)
{
// For example... passing a name parameter of "name1" will return a value of "100", etc.
// page.htm?name1=100&name2=101&name3=102
var winURL = window.location.href;
var queryStringArray = winURL.split("?");
var queryStringParamArray = queryStringArray[1].split("&");
var nameValue = null;
for ( var i=0; i<queryStringParamArray.length; i++ )
{
queryStringNameValueArray = queryStringParamArray[i].split("=");
if ( name == queryStringNameValueArray[0] )
{
nameValue = queryStringNameValueArray[1];
}
}
return nameValue;
}

Categories

Resources