I'm trying to create a Regex with jQuery so it will search for two words in an attribute of an XML file.
Can someone tell me how to return a result that contains BOTH words (sport and favorite) in any order and any case (upper or lower case)?
var regex = new RegExp("sport favorite", 'i');
var $result = $(data).filter(function() {
if($(this).attr('Description')) {
return $(this).attr('Description').match(regex);
}
});
If they may be separated by any character, you could do it like this:
var regex = new RegExp(".*sport.+favorite.*|.*favorite.+sport.*", 'i');
(This assumes that no other word in the attribute contains the substring favorite or sport.)
var regex = new RegExp("sport favorite|favorite sport", 'i');
The "\b" marker can be used to "match" the edges of words, so
var regex = /\bsport\b.*\bfavorite\b|\bfavorite\b.*\bsport\b/i;
matches the words only as words, and (for example) won't match "sporting his favorite hat".
Related
I have got of array symbols as shown below
var sourcesymbols = ["ERT", "UBL" , "AMAZING"];
I am getting the following news title from rss feed
you experts are amazing
How to check if the content present in the rssfeedstring is present under the sourcesymbols array or not ??
For example rssfeedstring has word amazing and it is also present under sourcesymbols
please let me know how to achive this .
I have tried to convert the rssfeedstring to uppercase then i am not sure how to use the indexOf on the string .
rssfeedstring = rssfeedstring.toUpperCase();
please let em know if there is any better approach also for doing this as the array will have 2000 symbols
http://jsfiddle.net/955pfz01/3/
You can use regex.
Steps:
Convert the array to string with join using |(OR in regex) as glue
Use \b-word boundary to match exact words
Use i flag on regex to match irrespective of the case. So, don't have to change the case of string.
Escape the slashes as using RegExp constructor requires string to be passed and \ in string is used as escape following character.
test can be used on regex to check if the string passes the regex.
var sourcesymbols = ["ERT", "UBL", "AMAZING"];
var mystr = 'you experts are amazing';
var regex = new RegExp("\\b(" + sourcesymbols.join('|') + ")\\b", 'i'); // /\b(ERT|UBL|AMAZING)\b/i
alert(regex.test(mystr));
You can also use some
Convert the string to array by using split with \s+. This will split the string by any(spaces, tabs, etc) one or more space character
Use some on splitted array
Convert the string to uppercase for comparing
Check if the element is present in array using indexOf
var mystr = 'you experts are amazing';
var sourcesymbols = ["ERT", "UBL", "AMAZING"];
var present = mystr.toUpperCase().split(/\s+/).some(function(e) {
return sourcesymbols.indexOf(e) > -1;
});
alert(present);
Try using Array.prototype.map() , Array.prototype.indexOf() to return matched text, index of matched text within sourcesymbols
var sourcesymbols = ["ERT", "UBL" , "AMAZING"];
var mystr = 'you experts are amazing';
var res = mystr.split(" ").map(function(val, index) {
var str = val.toUpperCase(), i = sourcesymbols.indexOf(str);
return i !== -1 ? [val, i] : null
}).filter(Boolean);
console.log(res)
jsfiddle http://jsfiddle.net/955pfz01/6/
Hi all I tried to create some regex with random value.
var data = "demo purpose?"; **OR** var data = "demo purpose";
var sentence = "can I put these app as demo purpose?";
var re = new RegExp("\\b(" + data + ")\\b", "g");
console.log(sentence.match(re)); // output ["demo purpose"]
In variable data have two different value demo purpose? & demo purpose with only question mark. Both console out are same please any one Give me hint what should i do in these case.
-
Thank you
you need to escape ? (i.e. write \\?) or else it would be interpreted as a quantifier in regex.
Furthermore, the \\b is not really necessary because it tries to match a non blank char in which case there is nothing behind demo purpose? so sentence.match(new RegExp("\\b(demo purpose\\?)\\b", "g")) would return null.
If you want randomness, use Math.random. Make an array and get an random integer or 0 or 1 (with Math.floor) as the index.
In order to pass variables into JS regex when using constructor notation, you need to escape all characters that act as regex special characters (quantifiers, group delimiters, etc.).
The escape function is available at MDN Web site:
function escapeRegExp(string){
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
Note also, that \b is a word boundary, and it prevents from matching the strings you need as ? is a non-word character. If you do not need to match word boundaries, remove \b. If you need to check if the search word is a whole word, use (?:^|\W) at the beginning and (?!\w) at the end and use exec rather than match to obtain access to the captured group 1.
So, your code will become:
function escapeRegExp(string){
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
var data = "demo purpose?";
var sentence = "can I put these app as demo purpose?";
var re = new RegExp("(?:^|\\W)(" + escapeRegExp(data) + ")(?!\\w)", "g");
while ((m = re.exec(sentence)) !== null) {
console.log(m[1]); // output ["demo purpose?"]
}
If you search for emo purpose?, no result will be returned since there will be no match.
This
var data = "demo purpose?"; // **OR** var data = "demo purpose";
var sentence = "can I put these app as demo purpose?";
var re = new RegExp(/demo purpose\?/, "g");
console.log(sentence.match(re)); // output ["demo purpose?"]
return ["demo purpose?"],
changing RegExp("xxx", "g"); to RegExp(/xxx/, "g");
You can do
var data = /demo purpose\?/; // **OR** var data = "demo purpose";
var sentence = "can I put these app as demo purpose?";
var re = new RegExp(data, "g");
console.log(sentence.match(re));
and you will get the same output
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']
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");
I'm trying to return the number of times a letter appears in a word.
I'm passing the letter to a function like so
function getCount(letter)
{
var pattern = '/' + letter + '/g';
var matches = word.match(pattern);
return matches.length;
}
Unfortunately matches is null so I'm unable to call length on it, I know the letter appears in the word as I've already checked that
word.indexOf(letter) > -1
I suspect the problem is with the way I'm building or evaluating pattern
Here's how you build a non literal regular expression :
var pattern = new RegExp(letter, 'g');
See the MDN on building a regular expression.
And here's a simpler solution to count the occurrences of the letter :
return word.split(letter).length-1;
You can do this:
function hasClass(letter) {
var pattern = new RegExp(letter,'g'); // Create a regular expression from the string
var matches = word.match(pattern);
return matches;
Ref: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/RegExp
This was also answered here: javascript new regexp from string