I've searched a lot questions to find a way to a Regex that matches a whole word only. I came up with several answers and questions but a lot of them are not what I need.
For example one of the best rated question on SO shows up with this solution:
let regx = new RegExp( "(^|\s)element-pattern(?=\s|$)" );
let text = "element-pattern";
if(text.match(regx)) {
console.log("in it");
}
text = "element-pattern has-variations";
if(text.match(regx)) {
console.log("in it");
} else {
console.log("not in");
}
The problem I have is that it matches too good for me. In my example the second statement should also be true. What can I change on my RegEx so that it don't fails the second time?
I think the issue is that you are creating a RegExp object from a string. When you use backslash (\) in a regular JS string, it is interpreted as an escape character, so \s becomes just s. Use a RegExp literal instead. You could also just escape the backslashes like new RegExp( "(^|\\s)element-pattern(?=\\s|$)" ), but I prefer the literal notation.
let regx = /(^|\s)element-pattern(?=\s|$)/
let text = "element-pattern";
if(text.match(regx)) {
console.log("in it");
}
text = "element-pattern has-variations";
if(text.match(regx)) {
console.log("in it");
} else {
console.log("not in");
}
Related
Who can help me with the following
I create a rule with regex and I want remove all characters from the string if they not allowed.
I tried something by myself but I get not the result that I want
document.getElementById('item_price').onkeydown = function() {
var regex = /^(\d+[,]+\d{2})$/;
if (regex.test(this.value) == false ) {
this.value = this.value.replace(regex, "");
}
}
The characters that allowed are numbers and one komma.
Remove all letters, special characters and double kommas.
If the user types k12.40 the code must replace this string to 1240
Who can help me to the right direction?
This completely removes double occurrences of commas using regex, but keeps single ones.
// This should end up as 1,23243,09
let test = 'k1,23.2,,43d,0.9';
let replaced = test.replace(/([^(\d|,)]|,{2})/g, '')
console.log(replaced);
I don't believe there's an easy way to have a single Regex behave like you want. You can use a function to determine what to replace each character with, though:
// This should end up as 1232,4309 - allows one comma and any digits
let test = 'k12,3.2,,43,d0.9';
let foundComma = false;
let replaced = test.replace(/(,,)|[^\d]/g, function (item) {
if (item === ',' && !foundComma) {
foundComma = true;
return ',';
} else {
return '';
}
})
console.log(replaced);
This will loop through each non-digit. If its the first time a comma has appeared in this string, it will leave it. Otherwise, if it must be either another comma or a non-digit, and it will be replaced. It will also replace any double commas with nothing, even if it is the first set of commas - if you want it to be replaced with a single comma, you can remove the (,,) from the regex.
I may just be being thick here but I don't understand why I am receiving this error. Outside of the function the .test() works fine. But inside, I get the error. Was thinking it was something to do with the scope of the .test() function but am I just missing something blindingly obvious here?
function cFunctionfirst() {
firstField = document.getElementById("sname_input_first").value;
document.getElementById("demo").innerHTML = "first: " + firstField;
console.log(firstField);
var regex = "!##$£%^&*()+=[]\\\';,./{}|\":<>?";
if(regex.test(firstField)){
console.log('illegal characters used');
} else {
console.log('Character okay');
};
};
That's because regex is not a RegExp object, but just a string. It should be declared as such (remember to escape special characters using \):
var regex = /[!##\$£%\^&\*\(\)\+=\[\]\\\';,\.\/\{\}\|":<>\?]/;
Not only have I escaped some special regex characters, but you will need to wrap the entire selection inside unescaped [ and ] brackets, so that you test against a set of characters.
p/s: These are the set characters that need to be escaped: \ ^ $ * + ? . ( ) | { } [ ]
See proof-of-concept example:
function cFunctionfirst(value) {
var regex = /[!##\$£%\^&\*\(\)\+=\[\]\\\';,\.\/\{\}\|":<>\?]/;
if(regex.test(value)){
console.log('illegal characters used');
} else {
console.log('Character okay');
};
};
cFunctionfirst('Legal string');
cFunctionfirst('Illegal string #$%');
Alternatively, if you don't want to manually escape the characters, you can either use a utility method to do it, or use an ES6 non-regex approach, which is probably a lot less efficient: checkout the JSPerf test I have made. Simply add the blacklisted characters literally in a string, split it, and then use Array.prototype.some to check if the incoming string contains any of the blacklisted characters:
function cFunctionfirst(value) {
var blacklist = '!##$£%^&*()+=[]\\\';,./{}|":<>?'.split('');
if (blacklist.some(char => value.includes(char))) {
console.log('illegal characters used');
} else {
console.log('Character okay');
};
};
cFunctionfirst('Legal string');
cFunctionfirst('Illegal string #$%');
This question already has answers here:
Why do regex constructors need to be double escaped?
(5 answers)
Closed 6 years ago.
The following regex check is not working in the code. But if i use this pattern at regex101.com it works perfectly
var pattern = "^([a-zA-Z0-9]([-\.\w]*[a-zA-Z0-9])*#([a-zA-Z0-9][-\w]*[a-zA-Z0-9]\.)+[a-zA-Z]{2,9})$";
var value = "test#user.com";
var regexp = new RegExp(pattern);
if (!regexp.test(value)) {
alert("Failed");
} else {
alert("passed");
}
Could you please help me why this is happening here. By the way if i make some modifications like given below, it works. But i want it to work with (new RegExp(pattern))
var pattern = /^([a-zA-Z0-9]([-\.\w]*[a-zA-Z0-9])*#([a-zA-Z0-9][-\w]*[a-zA-Z0-9]\.)+[a-zA-Z]{2,9})$/;
var value = "test#user.com";
if (!pattern.test(value)) {
alert("Failed");
} else {
alert("passed");
}
Just remove the double quotes and put your Regex simply in forward slashes.
var pattern = /^([a-zA-Z0-9]([-\.\w]*[a-zA-Z0-9])*#([a-zA-Z0-9][-\w]*[a-zA-Z0-9]\.)+[a-zA-Z]{2,9})$/;
var value = "test#user.com";
var regexp = new RegExp(pattern);
if (!regexp.test(value)) {
alert("Failed");
} else {
alert("passed");
}
It's because, if you're putting double quotes, then you need to escape your regular expression
However, you can simply put your regular expression as it is when placing it between forward slashes.
You need to escape those backslashes (\).
var pattern = "^([a-zA-Z0-9]([-\\.\\w]*[a-zA-Z0-9])*#([a-zA-Z0-9][-\\w]*[a-zA-Z0-9]\\.)+[a-zA-Z]{2,9})$";
var value = "test#user.com";
var regexp = new RegExp(pattern);
if (!regexp.test(value)) {
console.log("Failed");
} else {
console.log("passed");
}
I think I have all my ducks in order here, I am attempting to search my UL list using brackets either using a left one ( or a right one ) and I am getting a JavaScript kick back error:
"Expected '(' in regular expression".
I am by no means a regex expert here but what exactly could be the problem, i'd like to ideally be able to search using by any letters, numbers or special characters of my choosing in my input box without having the error as I described above.
Using Ie. 11, Fiddle is here: http://jsfiddle.net/acbabis/4cfQ8/show/
jQuery friendly:
$('#refdocs').on('keyup change', function () {
var search = $(this).val();
$('#refdocs_list li').each(function () {
var val = $(this).text();
$(this).toggle( !! val.match(search)).html(
val.replace(search, function(match) {return '<span style="background-color: #FFFF00">'+match+'</span>'}, 'gi')
);
});
});
Well, if I understand the error correctly, it's because your special characters are getting interpreted as regex function characters, which means they'll need to be escaped. Check out this answer:
Escape string for use in Javascript regex
As #LawrenceJohnson already pointed out, you have to escape any re special characters you wish to use in your search string. The following line shows you how to escape ( and ) but you can extend the list to escape more characters. Take a look at the demo -- url supplied at the bottom:
var search = $(this).val().replace(/([\(\)])/,'\\$1');
The rest of your code was not touched at all.
WORKING JS FIDDLE DEMO
To keep the regex match functionality. You can wrap you .match method inside a try catch block. Also, in order to highlight regex matched results, we have to pass an regex obj into val.replace.
$('#refdocs').on('keyup', function () {
var search = $(this).val();
$('#refdocs_list li').each(function () {
var val = $(this).text();
try {
$(this).toggle( !! val.match(search)).html(
val.replace(new RegExp(search, 'gi'), function (match) {
return '<mark>' + match + '</mark>'
}, 'gi'));
} catch(err) {
//console.log(err);
}
});
});
demo: http://jsfiddle.net/4cfQ8/4/
How do I do a .match on a string that has parentheses in the string?
String1.match("How do I match this (MATCH ME)");
None of the answers are getting me what I want. I'm probably just doing it wrong. I tried to make my question basic and I think doing that asked my question wrong. This is the statement I am tring to fix:
$('[id$=txtEntry3]').focus(function () {
if (!DropdownList.toString().match($('[id$=txtEntry2]').val()) || $('[id$=txtEntry2]').val().length < 5) {
$('[id$=txtEntry2]').select();
ErrorMessageIn("The Ingredient number you entered is not valid.");
return;
}
ErrorMessageOut();
});
This works correctly the problem I am running into is when it tries to match a entry from "txtEntry2" that has "()" in it.
Well it's kinda broken but it works for what I need it to do. This is what I did to fix my problem:
$('[id$=txtEntry3]').focus(function () {
if (!StripParentheses(DropdownList).match(StripParentheses($('[id$=txtEntry2]').val())) || $('[id$=txtEntry2]').val().length < 5) {
$('[id$=txtEntry2]').select();
if (!$('[id$=txtEntry2]').val() == "") {
ErrorMessageIn("The Ingredient number you entered is not valid.");
}
return;
}
ErrorMessageOut();
});
function StripParentheses(String){
x = String.toString().replace(/\(/g, '');
x = x.toString().replace(/\)/g, '');
return x;
}
to get all occurences in e.g. ".. (match me) .. (match me too) .." add the g regexp flag
string.match(/\((.*?)\)/g)
this as also an advantage, that you get only list of all occurences. without this flag, the result will include a whole regexp pattern match (as the first item of resulting array)
If you are interested in the part of the string between parenthesis, then you can use /\(([^\)]*)\)/; if you just need to get the full string, then you can you can use /\([^\)]*\)/.
var str = "How do I match this (MATCH ME)";
str.match(/\((.*?)\)/);