regex exact match in function - javascript

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

Related

Javascript replace string function

I have a script I'm trying to write which takes a string and finds the dmcode then sends it to a function to format it correctly then returns the value. This seems to work but I can't get the replace function to work on the string calling it. This has got to be easy but everything I've tried has resulted in errors.
Your help is appreciated.
Max
function scrubDMC(DM){
var dmcode = DM;
for (var i = 0; i < dmcode.length; i++) {
DMC = dmcode[i];
match = DMC.match(/modelIdentCode="(.*?)"/im);
if (match !== null) {
var modelIdentCode = match[1];
}
match = DMC.match(/systemDiffCode="(.*?)"/im);
if (match !== null) {
var systemDiffCode = match[1];
}
match = DMC.match(/\ssubSystemCode="(.*?)"/im);
if (match !== null) {
var subSystemCode = match[1];
}
match = DMC.match(/subSubSystemCode="(.*?)"/im);
if (match !== null) {
var subSubSystemCode = match[1];
}
}
var sFileName = "DMC-" + modelIdentCode +"-"+ systemDiffCode +"-"+ systemCode + "-" + subSystemCode + subSubSystemCode + "-" + assyCode +"-"+ disassyCode + disassyCodeVariant +"-" + infoCode +infoCodeVariant +"-" +itemLocationCode;
console.log("sFileName : " + sFileName);
return sFileName;
}
Code calling the function that isn't working
var readyWarn2 = readyWarn.replace(/<symbol infoEntityIdent=".*?"\/>/ig, "");
var dmcode = readyWarn2.match(/<dmcode.*?>/ig);
scrubDMC(dmcode);
readyWarn2.replace(dmcode, sFileName);
Your last line needs to be
readyWarn2 = readyWarn2.replace(dmcode, sFileName);
Javascript strings can't be changed, so String.replace() returns a new string value.

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));
});

Removing final part of URL in Javascript/Jquery

I have some URL's that all follow the same structure.
https://www.website.com/services/county/town/servicename/brand/
When the search has zero results we display a button that when clicked runs a function to remove the final section of the URL and thus expand the search.
For example if the above URL returned 0 results then clicking our button would load https://www.website.com/services/county/town/servicename/ having removed brand from the search criteria and expanding the chance of results.
The code I currently have for this works but seems like a bit of a hack.
function expandSearch() {
var currentURL = window.location.href;
var parts = currentURL.split("/");
var lastPart;
if ( parts.length === 9 ) {
lastPart = currentURL.substr(currentURL.lastIndexOf('/') - parts[7].length) + '$';
window.location.href = currentURL.replace( new RegExp(lastPart), "");
} else if ( parts.length === 8 ) {
lastPart = currentURL.substr(currentURL.lastIndexOf('/') - parts[6].length) + '$';
window.location.href = currentURL.replace( new RegExp(lastPart), "");
} else if ( parts.length === 7 ) {
lastPart = currentURL.substr(currentURL.lastIndexOf('/') - parts[5].length) + '$';
window.location.href = currentURL.replace( new RegExp(lastPart), "");
} else if ( parts.length === 6 ) {
lastPart = currentURL.substr(currentURL.lastIndexOf('/') - parts[4].length) + '$';
window.location.href = currentURL.replace( new RegExp(lastPart), "");
}
}
The search can return 0 results at any point down to https://www.website.com/services/ at which point the whole database is returned.
The URL can also have missing elements for example it might have a county but no town.
Is there a better/cleaner way of removing the final URL element and redirecting the browser to this new broader search?
The final working version I ended up with thanks to #ebilgin for anyone looking:
function expandSearch() {
var parts = window.location.pathname.substr(1).split("/");
parts = parts.filter(Boolean); // Remove trailing empty array object
parts.pop(); // Remove last array object
window.location.href = "/" + parts.join("/") + "/"; // Go to new Location
}
You can use .pop() and .join() functions for your problem.
function expandSearch() {
var parts = window.location.pathname.substr(1);
var lastCharIsSlash = false;
if ( parts.charAt( parts.length - 1 ) == "/" ) {
lastCharIsSlash = true;
parts = parts.slice(0, -1);
}
parts = parts.split("/");
parts.pop();
parts = "/" + parts.join("/") + (lastCharIsSlash ? "/" : "");
window.location.href = parts;
}
If your every URIs has a trailing slash. This is much more clearer version of it.
function expandSearch() {
var parts = window.location.pathname.slice(1, -1).split("/");
parts.pop();
window.location.href = "/" + parts.join("/") + "/";
}

Regex exact text match is not working

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>

Categories

Resources