Find all words containing specific letters and special characters - javascript

Suppose I have a list formed by words including special characters:
one
<two></two>
three#
$four
etc.
I want to find all words in the list that contain specific letters,
I've tried to use
var myList = "<one></one> $two three#";
var myRegex = /\bMYWORD[^\b]*?\b/gi;
alert(myList.match(myRegex));
But this does not work with special characters..
DEMO
Unfortunately I'm new to javascript, and I don't know what is the best way to create the list
and to separe the words in the list..

So based on your inputs, this does the trick:
var myList = "<one></one> $two three#";
var items = myList.split(' ');
$('#myInput').on('input',function(){
var matches = [];
for(var i = 0; i < items.length; i++) {
if(items[i].indexOf(this.value) > -1)
matches.push(items[i]);
}
$('#myDiv').text(matches.join(','));
});
Is this what you want?

If I understand correctly, all you need is to escape all special characters from your query string so that they are not considered as such by the RegEx engine. Something like this should work:
var myList = "<one></one> $two three#";
var query = "$two";
var myRegex = new RegEx(query.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"));
alert(myList.match(myRegex));
Hat tip to the answer that provided the escaping mechanism.
Is this what you needed?
PD: I'd also recommend using console instead of alert.

Related

RegEx - JavaScript .match() with a variable keyword

I have a string with keywords, separated by comma's.
Now I also have a nice RegEx, to filter out all the keywords in that string, that matches a queried-string.
Check out this initial question - RegEx - Extract words that contains a substring, from a comma seperated string
The example below works fine; it has a masterString, and a resultString. That last one only contains the keywords that has at least the word "car" in it.
masterString = "typography,caret,car,align,shopping-cart,adjust,card";
resultString = masterString.match(/[^,]*car[^,]*/g);
console.log(resultString);
Result from the code above;
"caret", "car", "shopping-cart", "card"
But how can I use the RegEx, with a variable matching-word (the word "car" in this example static and not variable).
I think it has to do something with a RegExp - but I can't figure out...
Here's a general solution for use with regexes:
var query = "anything";
// Escape the metacharacters that may be found in the query
// sadly, JS lacks a built-in regex escape function
query = query.replace(/[-\\()\[\]{}^$*+.?|]/g, '\\$&');
var regex = new RegExp("someRegexA" + query + "someRegexB", "g");
As long as someRegexA and someRegexB form a valid regex with a literal in-between, the regex variable will always hold a valid regex.
But, in your particular case, I'd simply do this:
var query = "car";
var items = masterString.split(",");
query = query.toLowerCase();
for (var i = 0; i < items.length; ++i) {
if (items[i].toLowerCase().indexOf(query) >= 0) {
console.log(items[i]);
}
}
How about this one?, you only need to replace \ \ with String , and it works for me. it can find whether your string has "car", not other similar word
var query = 'car';
var string = "car,bike,carrot,plane,card";
var strRegEx = '[^,]*'+query+'[,$]*';
string.match(strRegEx);
Answer provided by OP and removed from inside the question
I figured out this quick-and-maybe-very-dirty solution...
var query = 'car';
var string = "car,bike,carrot,plane,card";
var regex = new RegExp("[^,]*|QUERY|[^,]*".replace('|QUERY|',query),'ig');
string.match(regex);
This code outputs the following, not sure if it is good crafted, 'though..
"car", "carrot", "card"
But ended figuring out another, much simpler solution;
var query = "car";
var string = "car,bike,carrot,plane,card";
string.match(new RegExp("[^,]*"+query+"[^,]*",'ig'));
This code outputs the string below;
["car", "carrot", "card"]
My app-search-engine now works perfect :)

How to match an out of order string with Javascript regular expressions

I've written a live filter in javascript that takes a value from a field and hides the rows in a table that do not match.
The RegEx I use for this is very simple: /inputValue/i
Although this works great it only matches characters that are in order. For example:
inputValue = test
string to match = this is a test sentence
This example would match, but if I tried:
inputValue = this sentence
string to match = this is a test sentence
This won't match because the input value is out of order.
How would I go about writing a RegEx that is in order but can skip words?
Here is the loop I currently use:
for (var i=0; i < liveFilterDataArray.length; i++) {
var comparisonString = liveFilterDataArray[i],
comparisonString = comparisonString.replace(/['";:,.\/?\\-]/g, '');
RE = eval("/" + liveFilterValue + "/i");
if (comparisonString.match(RE)) {
rowsToShow.push(currentRow);
}
if(currentRow < liveFilterGridRows.length - 1) {
currentRow++;
} else {
currentRow = 0;
}
}
Many thanks for your time.
Chris
It is recommended to Use RegExp instead of eval.
DEMO
var words = liveFilterValue.split(" ");
var searchArg = (words.length==1)?words:words.join(".*")+'|'+words.reverse().join(".*")
var RE = new RegExp(searchArg,"i");
It will create this.*sentence|sentence.*this/i
remove +'|'+words.reverse().join(".*") if you only want to find this.....sentence and not sentence....this
You could split the input string on spaces and then run the filter sequentially for each word.

Extracting Strings Into an Array Regex

I'm almost there! Just can't figure out the last part of what I need... forming the array.
I want to go through an html file and extract url's from between the phrases playVideo(' and ')
For testing purposes I am just trying to get it to work on the variable str, eventually this will be replaced by the html document:
<script type="text/javascript">
var str ="playVideo('url1') BREAK playVideo('url2') BREAK playVideo('url3')";
var testRE = str.match("playVideo\\(\'(.*?)\'");
alert(testRE[1]);
</script>
This will output 'url1' but if I change it to alert(testRE[2]) it is undefined. How can I get it to fill out the array with all of the URLs (eg testRE[2] output 'url2' and so on) ?
Thanks for any help, new to regex.
Cannot comment, why is that, but adding that by iterating on the regex you get access to the groups;
var str ="playVideo('url1') BREAK playVideo('url2') BREAK playVideo('url3')";
var re = /playVideo\('(.*?)'\)/g;
while (match = re.exec(str)) {
alert(match[1]);
}
Normally a javascript regular expression will just perform the first match. Update your regular expression to add the g modifier. Unfortunately JavaScript regular expressions don't have a non-capturing group so you have to do a little more processing to extract the bit you want e.g.
<script type="text/javascript">
var str ="playVideo('url1') BREAK playVideo('url2') BREAK playVideo('url3')";
var testRE = str.match(/playVideo\(\'[^']*\'/g);
var urls = [];
for (var i = 0; i < testRE.length; i++)
{
urls[i] = testRE[i].substring(11).match(/[^']*/);
}
alert(urls[1]);
alert(urls[2]);
</script>

Splitting a String by an Array of Words in Javascript

I'm taking some text and want to split it into an array. My goal is to be able to split it into phrases delimited by stopwords (words ignored by search engines, like 'a' 'the' etc), so that I can then search each individual phrase in my API. So for example: 'The cow's hat was really funny' would result in arr[0] = cow's hat and arr[1] = funny. I have an array of stopwords already but I can't really think of how to actually split by each/any of the words in it, without writing a very slow function to loop through each one.
Use split(). It takes a regular expression. The following is a simple example:
search_string.split(/\b(?:a|the|was|\s)+\b/i);
If you already have the array of stop words, you could use join() to build the regular expression. Try the following:
regex = new RegExp("\\b(?:" + stop_words.join('|') + "|\\s)+\\b", "i");
A working example http://jsfiddle.net/NEnR8/. NOTE: it may be best to replace these values than to split on them as there are empty array elements from this result.
This does a case insensitive .split() on your keywords, surrounded by word boundries.
var str = "The cow's hat was really funny";
var arr = str.split(/\ba\b|\bthe\b|\bwas\b/i);
You may end up with some empty items in the Array. To compact it, you could do this:
var len = arr.length;
while( len-- ) {
if( !arr[len] )
arr.splice( len, 1);
}
Quick and dirty way would be to replace the "stop word" strings with some unique characters (e.g. &&&), and then split based on that unique character.
For example.
var the_text = "..............",
stop_words = ['foo', 'bar', 'etc'],
unique_str = '&&&';
for (var i = 0; i < stop_words.length; i += 1) {
the_text.replace(stop_words[i], unique_str);
}
the_text.split(unique_str);

JavaScript split function

i like to split a string depending on "," character using JavaScript
example
var mystring="1=name1,2=name2,3=name3";
need output like this
1=name1
2=name2
3=name3
var list = mystring.split(',');
Now you have an array with ['1=name1', '2=name2', '3=name3']
If you then want to output it all separated by spaces you can do:
var spaces = list.join("\n");
Of course, if that's really the ultimate goal, you could also just replace commas with spaces:
var spaces = mystring.replace(/,/g, "\n");
(Edit: Your original post didn't have your intended output in a code block, so I thought you were after spaces. Fortunately, the same techniques work to get multiple lines.)
Just use string.split() like this:
var mystring="1=name1,2=name2,3=name3";
var arr = mystring.split(','); //array of ["1=name1", "2=name2", "3=name3"]
If you the want string version of result (unclear from your question), call .join() like this:
var newstring = arr.join(' '); //(though replace would do it this example)
Or loop though, etc:
for(var i = 0; i < arr.length; i++) {
alert(arr[i]);
}
You can play with it a bit here

Categories