finding a matching patterns from the list of elements - javascript

I am trying to find matching patterns for the string that a user enters in to textbox, i was successful with the code in most cases with my code, bt ive found in some cases, it doesnt return all the needed results. I am attaching a jsfiddle link to show its wrking, I will also paste the code for future references
http://jsfiddle.net/faphf/2/
$("#facetSearchBox").live("keyup",
function() {
$("#test").empty();
facetSearch();
});
function facetSearch(){
var facetSearchTerm = $("#facetSearchBox").val();
facetSearchTerm = facetSearchTerm.toLowerCase();
var inputArray=["mark zuckerberg","ben s bernanke","ben bernanke","sven grundberg", "michael bloomberg","robert powell","kenneth lieberthal","frank boulben"];
var re = new RegExp(facetSearchTerm, "ig");
var outputArray = inputArray.filter(function(item) {
return re.test(item);
});
for(var k=0; k<outputArray.length;k++){
$("#test").append(outputArray[k] + "<br>" );
}
}
Try searching ben, it will not return all the desired results... it would be helpful if you could help me tell what is wrong with the code?

Remove the global modifier g from your Regular expression. It should work fine after that.
var re = new RegExp(facetSearchTerm, "i");
Test Link: http://jsfiddle.net/faphf/5/
EDIT:
Why RegExp with global flag in Javascript give wrong results?

Use:
var re = new RegExp( facetSearchTerm, "i");
See:fiddle
For word boundary matching:
var re = new RegExp("\\b" + facetSearchTerm, "i");
See:fiddle

Related

Regular expression to eliminate a word

I have this string:
var chain = "providerId=12$familyId=123&brandId=1122112$officeId=21&";
I need to do a method that erases a certain word with regular expressions.
Example:
var word = "familyId";
var newChain = deleteParam(chain, word);
console.log(newChain);
Result = "providerId=12$brandId=1122112$officeId=21&";
Delete : familyId=123&
I tried to do the method in the following way, but it does not work:
function deleteParam(chain, word) {
var exp = new RegExp(param, "=[0-9]&");
var str = chain.replace(exp, ""); // Delete
return str
}
Please, I need your help, I can not make this method work, because I do not understand well how to build regular expressions.
Excuse me all, English is not my native language
thank you very much to all.
You can use something like this new RegExp(param + "=\[^&]+")
Here is an example:
var chain = "providerId=12$familyId=123&brandId=1122112$officeId=21&";
var toRemove = "familyId";
var pattern = new RegExp(toRemove + "=[^&]*&");
var newChain = chain.replace(pattern, "");
console.log(newChain);
If you're looking to process a GET request's search parameters is better to use a pattern like this (&|\?)*parameterName=[^&]*

jQuery Regex from String

I have the following Regex that comes from a data Attribute on an HTML Element:
/^$|^[0-9]{2}.[0-9]{4}$/g
When I (manually) do:
/^$|^[0-9]{2}.[0-9]{4}$/g.test('01.2012');
It works and returns true.
When I put the Regex in a Variable like so:
var inputRegex = $(this).attr('data-validation');
And do:
inputRegex.test(input);
I get:
inputRegex.test is not a function.
I know that this is because inputRegex is a String and String does not have a test function, but when I create a RegExp object (new RegExp($(this).attr('data-validation')) it breaks my Regular Expression by escaping:
/\/^$|^[0-9]{2}.[0-9]{4}$\/g/
How can I use the data-attribute value as a Regular Expression? Please note that I cannot do: var regex = new RegExp(string, 'g'); because the Regular Expression(s) come predefined from the attribute.
var pattern = '\d+';
var regExp = new RegExp(pattern, 'g');
'1234dasf13241234'.match(regExp)
is it what you need?
var pattern = $(this).attr('data-validation');;
var regExp = new RegExp(pattern, 'g');
regExp.test(input);
in your case
your problem is that you need to retrieve the regex pattern from a attribute of an element, but it is returning string, and you want the string value to be like inline on your javascript code, like declaring plainly a regex. If this is really what you want to achieve, the closest solution is to use eval function, see updated code below:
var stringreg = "var inputRegex =" + $("#test").attr('data-validation') + ";"
eval(stringreg);
inputRegex.test(input);
This could help
var validation = "/^$|^[0-9]{2}.[0-9]{4}$/g"; //$(this).attr('data-validation')
var startIndex = validation.indexOf('/')+1
var lastIndex = validation.lastIndexOf('/');
var pattern = validation.substring(startIndex,lastIndex);
var options = validation.substring(lastIndex+1);
var regExp = new RegExp(pattern, options);
regExp.test('01.2012');
// true

Regular Expression to match compound words using only the first word

I am trying to create a regular expression in JS which will match the occurences of box and return the full compound word
Using the string:
the box which is contained within a box-wrap has a box-button
I would like to get:
[box, box-wrap, box-button]
Is this possible to match these words only using the string box?
This is what I have tried so far but it does not return the results I desire.
http://jsfiddle.net/w860xdme/
var str ='the box which is contained within a box-wrap has a box-button';
var regex = new RegExp('([\w-]*box[\w-]*)', 'g');
document.getElementById('output').innerHTML=str.match(regex);
Try this way:
([\w-]*box[\w-]*)
Regex live here.
Requested by comments, here is a working example in javascript:
function my_search(word, sentence) {
var pattern = new RegExp("([\\w-]*" + word + "[\\w-]*)", "gi");
sentence.replace(pattern, function(match) {
document.write(match + "<br>"); // here you can do what do you want
return match;
});
};
var phrase = "the box which is contained within a box-wrap " +
"has a box-button. it is inbox...";
my_search("box", phrase);
Hope it helps.
I'll just throw this out there:
(box[\w-]*)+
You can use this regex in JS:
var w = "box"
var re = new RegExp("\\b" + w + "\\S*");
RegEx Demo
This should work, note the 'W' is upper case.
http://www.w3schools.com/jsref/jsref_obj_regexp.asp
\Wbox\W
It looks like you're wanting to use the match with a regex. Match is a string method that will take a regex as an argument and return an array containing matches.
var str = "your string that contains all of the words you're looking for";
var regex = /you(\S)*(?=\s)/g;
var returnedArray = str.match(regex);
//console.log(returnedArray) returns ['you', 'you\'re']

Why replace() with regex change condition not result

I have the following code:
var code = $('#code');
var str = code.val();
console.log(str);
var re = new RegExp("^press\\\(\\\"" + "KEY_6" + "\\\"\\\)\\n+(.*)", "m");
console.log(re);
var res = str.replace(re,'');
console.log(res);
code.val(res);
When a user inputs this into textarea:
press("KEY_3")
press("KEY_6")
press("KEY_9")
It should replace press("KEY_9") with empty string. However, it also replaces the condition press("KEY_6")
Could you help me to understand possible reasons why it's not working as supposed? There's following link with example: http://jsfiddle.net/vfn8dtn4/
You should capture the group you want to keep, and then replace with $1:
...
var re = new RegExp("^([\\s\\S]*press\\\(\\\"" + "KEY_6" + "\\\"\\\))[\\n\\r]+.*", "m");
console.log(re);
var res = str.replace(re,'$1');
...
See updated code
Output:
press("KEY_6")
press("KEY_1")
press("KEY_6")
When we add [\\s\\S]* at the pattern start, we make sure we match as many characters as possible before the first press, so we'll capture the last KEY_6.
The (.*) at the end is consuming all the characters coming after "KEY_6" and the new line character. If you remove that i.e.
"^press\\\(\\\"" + "KEY_6" + "\\\"\\\)\n+"
works fine

Javascript RegExp match & Multiple backreferences

I'm having trouble trying to use multiple back references in a javascript match so far I've got: -
function newIlluminate() {
var string = "the time is a quarter to two";
var param = "time";
var re = new RegExp("(" + param + ")", "i");
var test = new RegExp("(time)(quarter)(the)", "i");
var matches = string.match(test);
$("#debug").text(matches[1]);
}
newIlluminate();
#Debug when matching the Regex 're' prints 'time' which is the value of param.
I've seen match examples where multiple back references are used by wrapping the match in parenthesis however my match for (time)(quarter)... is returning null.
Where am I going wrong? Any help would be greatly appreciated!
Your regex is literally looking for timequarterthe and splitting the match (if it finds one) into the three backreferences.
I think you mean this:
var test = /time|quarter|the/ig;
Your regex test simply doesn't match the string (as it does not contain the substring timequarterthe). I guess you want alternation:
var test = /time|quarter|the/ig; // does not even need a capturing group
var matches = string.match(test);
$("#debug").text(matches!=null ? matches.join(", ") : "did not match");

Categories