How to find any of the specific characters exists in a string - javascript

Im looking for a solution to search the existence of given characters in a string. That means if any of the given characters present in a string, it should return true.
Now am doing it with arrays and loops. But honestly I feel its not a good way. So is there is any easiest way without array or loop?
var special = ['$', '%', '#'];
var mystring = ' using it to replace VLOOKUP entirely.$ But there are still a few lookups that you are not sure how to perform. Most importantly, you would like to be able to look up a value based on multiple criteria within separate columns.';
var exists = false;
$.each(special, function(index, item) {
if (mystring.indexOf(item) >= 0) {
exists = true;
}
});
console.info(exists);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

try with regex
var patt = /[$%#]/;
console.log(patt.test("using it to replace VLOOKUP entirely.$ But there are still a few lookups that you are not sure how to perform. Most importantly, you would like to be able to look up a value based on multiple criteria within separate columns."));

Be aware that [x] in regEx is for single characters only.
If you say wanted to search for say replace, it's going to look for anything with 'r,e,p,l,a,c' in the string.
Another thing to be aware of with regEx is escaping. Using a simple escape regEx found here -> Is there a RegExp.escape function in Javascript? I've made a more generic find in string.
Of course you asked given characters in a string, so this is more of an addenum answer for anyone finding this post on SO. As looking at your original question of an array of strings, it might be easy for people to think that's what you could just pass to the regEx. IOW: your questions wasn't how can I find out if $, %, # exist in a string.
var mystring = ' using it to replace VLOOKUP entirely.$ But there are still a few lookups that you are not sure how to perform. Most importantly, you would like to be able to look up a value based on multiple criteria within separate columns.';
function makeStrSearchRegEx(findlist) {
return new RegExp('('+findlist.map(
s=>s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')).join('|')+')');
}
var re = makeStrSearchRegEx(['$', '%', '#', 'VLOOKUP']);
console.log(re.test(mystring)); //true
console.log(re.test('...VLOOKUP..')); //true
console.log(re.test('...LOOKUP..')); //false

The best way is to use regular expressions. You can read more about it here.
In your case you should do something like this:
const specialCharacters = /[$%#]/;
const myString = ' using it to replace VLOOKUP entirely.$ But there are still a few lookups that you are not sure how to perform. Most importantly, you would like to be able to look up a value based on multiple criteria within separate columns.';
if(specialCharacters.test(myString)) {
console.info("Exists...");
}
Please, note, that it is good approach to store regular expressions in a variable to prevent creating of regular expression (which is not the fastest operation) each time you use it.

Related

Quickly check if two regular expressions share matches

say I have a list of regular expressions, which match filepaths:
{
"list":[
"^/foo/bar/baz/x",
"^/foo/bar/baz/y"
"^/foo/mon/choo$",
...
"^/foo/.*"
]
}
Note that at runtime, this will happen:
let regexes = list.map(function(l){
return new RegExp(l);
});
I need to create a routine to quickly check if two or more of the regular expressions match the same input.
Is there a way to quickly check if an imaginary/potential filepath would match more than one regular expression in the list?
For example, the regular expression /foo/.* will match the first 3 items, and therefore that represents an error in my program.
Use case: the user is expected to create a list of regular expressions, but they have to be exclusive regular expressions which do not share any matches.
I could check this with actual input, but I am wondering if there is a way to check this with theoretical input as well. (I am hoping that latter would be faster).
The "hard" way: I have a list of files. For each file I check to see if it matches any of the regular expressions in the list. If it matches more than 1 in the list, I throw an error.
The problem with the hard way is that I would like to validate the list before using any real input data.
Since you're using an array, it's possible to have duplicates of the exact regex, so maybe you want to use an object with keys instead or just set it.
Along with that, you could actually use the regex themselves to test each other. In my example below I'm only checking .* or .+ but if you really want to be comprehensive, you could run each regex against every other regex. Though I didn't do this because it might have a really long run time, but that's up to you.
var list = [
"/foo/bar/baz/x",
"/foo/bar/baz/y",
"/foo/mon/choo$",
"/foo/.*"
];
var error_list = [...list, "/foo/mon/choo$"];
let set = new Set(error_list);
console.log(set.length === list.length, "\"if false it means there's duplicates\"");
var regexes = [];
for (var regex of list){
if (regex.match(/\.(\*|\+)/)){
regexes.push(regex);
}
}
loop:
for (var regex of regexes){
var r = new RegExp("^"+regex);
for (let test of list){
if (test.match(r) && regex !== test){
console.log(test, "this matched");
// break loop;
}
}
}

match css rules in javascript

I need to create a regular expression to find class inside a css file.
For example I have this css file:
#label-blu{
}
.label-blu, .test{
}
.label-blu-not-match{
}
.label-blu{
}
.label-blu span{
}
In this case I need to return 3 match
This is my regular expression:
var css = data;
var find_css = 'label-blu';
var found = css.match(/([#|\.]?)([\w|:|\s|\.]+)/gmi).length;
console.log('found: ' + found);
Inside var data there is all the css string
How can I solve?
Thanks
There are two points:
("word-does-not-include-hyphen").replace(/\w+/g, 'test')
And are you sure you should be matching against css label text label-blu? rather than the full css text itself? Currently you are finding the separations across the hyphen for label-blu...
var css = 'label-blu';
var found = css.match(/([#|\.]?)([\w|:|\s|\.]+)/gmi);
/// which gives ['label','blu']
Which is the reason for the returned length of two, rather than three. Were you not hoping to match the three items in the css text i.e
#label-blu
.label-blu-not-match
.label-blu
If so you will need to use a different text to match, the entire css, rather than just the string 'label-blue'.
However if you are trying to match:
#label-blu
.label-blu, .test
.label-blu
.label-blu span
Then you will need a different RegExp and the entire css string. Just need clarification on which route you need?
update
It's still not clear exactly out of the css text what you wish to match, this is the reason why I have outlined exactly. However, on the assumption you want to match the last four items I mention (and assuming you don't wish to match label-blu-not-match) then the following should help:
http://jsfiddle.net/5d7JX/
var found = csstext.match(/[#\.]label-blu([,:\s\.][^\{]*)?\{/gmi);
However the above is not full-proof for all possible css formats, nor does it protect against matches within the css rule-sets themselves. Generally speaking scanning through code that is usually quite complicated to parse into something logical using only Regular Expressions is frowned upon; unless you are solving a very specific use-case.
update 2
Yes excluding the ID selectors just involves removing the # part of the Reg Exp...
var found = csstext.match(/\.label-blu([,:\s\.][^\{]*)?\{/gmi);
I recommend that you read up on your regular expressions, this site is a good place:
http://www.regular-expressions.info/
update 3
To include a variable as part of a regular expression you will need to make sure you escape the characters to make the string literal, so any special characters wont interfere. As far as I'm aware there isn't a built in function to escape or quote for regular expressions in JavaScript; however you can find one here:
How to escape regular expression in javascript?
So if you add this to your code:
RegExp.quote = function(str) {
return (str+'').replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
};
You then also need to convert your regexp to the object equivalent:
var reg = new RegExp('\\.label-blu([,:\\s\\.][^\\{]*)?\\{', 'gmi');
var found = csstext.match(reg);
And then add this:
var label = 'label-blu';
var reg = new RegExp('\\.' + RegExp.quote(label) + '([,:\\s\\.][^\\{]*)?\\{', 'gmi');
var found = csstext.match(reg);
http://jsfiddle.net/5d7JX/1/
In your example if you use:
var findClass = /(\.label-blu)(?!-)+/g;
var found = css.match(findClass).length;
should return 3...
maybe a better solution is:
var findClass = /(\.label-blu)[\s{,]+/g;
var found = css.match(findClass).length;
to cover a possibility when you might have something else rather than '-' added to your wanted class and it will only look for the class that's followed by a 'space' a '{' or a ','...
let me know if you have any questions

Javascript Regex after specific string

I have several Javascript strings (using jQuery). All of them follow the same pattern, starting with 'ajax-', and ending with a name. For instance 'ajax-first', 'ajax-last', 'ajax-email', etc.
How can I make a regex to only grab the string after 'ajax-'?
So instead of 'ajax-email', I want just 'email'.
You don't need RegEx for this. If your prefix is always "ajax-" then you just can do this:
var name = string.substring(5);
Given a comment you made on another user's post, try the following:
var $li = jQuery(this).parents('li').get(0);
var ajaxName = $li.className.match(/(?:^|\s)ajax-(.*?)(?:$|\s)/)[1];
Demo can be found here
Below kept for reference only
var ajaxName = 'ajax-first'.match(/(\w+)$/)[0];
alert(ajaxName);
Use the \w (word) pattern and bind it to the end of the string. This will force a grab of everything past the last hyphen (assuming the value consists of only [upper/lower]case letters, numbers or an underscore).
The non-regex approach could also use the String.split method, coupled with Array.pop.
var parts = 'ajax-first'.split('-');
var ajaxName = parts.pop();
alert(ajaxName);
you can try to replace ajax- with ""
I like the split method #Brad Christie mentions, but I would just do
function getLastPart(str,delimiter) {
return str.split(delimiter)[1];
}
This works if you will always have only two-part strings separated by a hyphen. If you wanted to generalize it for any particular piece of a multiple-hyphenated string, you would need to write a more involved function that included an index, but then you'd have to check for out of bounds errors, etc.

Regular Expression with multiple words (in any order) without repeat

I'm trying to execute a search of sorts (using JavaScript) on a list of strings. Each string in the list has multiple words.
A search query may also include multiple words, but the ordering of the words should not matter.
For example, on the string "This is a random string", the query "trin and is" should match. However, these terms cannot overlap. For example, "random random" as a query on the same string should not match.
I'm going to be sorting the results based on relevance, but I should have no problem doing that myself, I just can't figure out how to build up the regular expression(s). Any ideas?
The query trin and is becomes the following regular expression:
/trin.*(?:and.*is|is.*and)|and.*(?:trin.*is|is.*trin)|is.*(?:trin.*and|and.*trin)/
In other words, don't use regular expressions for this.
It probably isn't a good idea to do this with just a regular expression. A (pure, computer science) regular expression "can't count". The only "memory" it has at any point is the state of the DFA. To match multiple words in any order without repeat you'd need on the order of 2^n states. So probably a really horrible regex.
(Aside: I mention "pure, computer science" regular expressions because most implementations are actually an extension, and let you do things that are non-regular. I'm not aware of any extensions, certainly none in JavaScript, that make doing what you want to do any less painless with a single pattern.)
A better approach would be to keep a dictionary (Object, in JavaScript) that maps from words to counts. Initialize it to your set of words with the appropriate counts for each. You can use a regular expression to match words, and then for each word you find, decrement the corresponding entry in the dictionary. If the dictionary contains any non-0 values at the end, or if somewhere a long the way you try to over-decrement a value (or decrement one that doesn't exist), then you have a failed match.
I'm totally not sure if I get you right there, so I'll just post my suggestion for it.
var query = "trin and is",
target = "This is a random string",
search = { },
matches = 0;
query.split( /\s+/ ).forEach(function( word ) {
search[ word ] = true;
});
Object.keys( search ).forEach(function( word ) {
matches += +new RegExp( word ).test( target );
});
// do something useful with "matches" for the query, should be "3"
alert( matches );
So, the variable matches will contain the number of unique matches for the query. The first split-loop just makes sure that no "doubles" are counted since we would overwrite our search object. The second loop checks for the individuals words within the target string and uses the nifty + to cast the result (either true or false) into a number, hence, +1 on a match or +0.
I was looking for a solution to this issue and none of the solutions presented here was good enough, so this is what I came up with:
function filterMatch(itemStr, keyword){
var words = keyword.split(' '), i = 0, w, reg;
for(; w = words[i++] ;){
reg = new RegExp(w, 'ig');
if (reg.test(itemStr) === false) return false; // word not found
itemStr = itemStr.replace(reg, ''); // remove matched word from original string
}
return true;
}
// test
filterMatch('This is a random string', 'trin and is'); // true
filterMatch('This is a random string', 'trin not is'); // false

Javascript RegEx match problem

I have a sentence structure along the lines of
[word1]{word2} is going to the [word3]{word4}
I'm trying to use a javascript regex to match the words for replacement later. To do this, I'm working towards getting the following multi-dimensional array:
[["word1", "word2"],["word3","word4"]]
I'm currently using this regex for the job:
\[(.*?)\]\{(.*?)\}
However, it comes up with results like:
["[word1]{word2}", "word1", "word2"]
or worse. I don't really understand why because this regex seems to work in Ruby just fine, and I'm not really much of a regex expert in general to understand what's going on. I'm just curious if there are any javascript rege expert's out there to whom this answer is very clear and can guide me along with what's going on here. I appreciate any help!
Edit:
This is the code I'm using just to test the matching:
function convertText(stringText) {
var regex = /\[(.*?)\]\{(.*?)\}/;
console.log(stringText.match(regex));
}
I assume you are using the exec method of the regular expression.
What you are doing is almost correct. exec returns an array where the first element is the entire match and the remaining elements are the groups. You want only the elements at indexes 1 and 2. Try something like this, but of course store the results into an array instead of using an alert:
var string = '[word1]{word2} is going to the [word3]{word4}';
var pattern = /\[(.*?)\]\{(.*?)\}/g;
var m;
while(m = pattern.exec(string)) {
alert(m[1] + ',' + m[2]);
}
This displays two alerts:
word1,word2
word3,word4
What you're seeing is Japanese hiragana. Make sure your input is in English maybe?
Edited to say: Upon further review, it looks like a dictionary entry in Japanese. The 私 is kanji and the わたし is hiragana, a phonetic pronunciation of the kanji. FWIW, the word is "Watashi" which is one of the words for "I" (oneself) in Japanese.

Categories