Reputation: 2133
I am having a dynamic variable which I need to match against a source.
Source: 'text clientLogin padding float';
search: '.clientLog'
The search text has a leading dot('.') which should be omitted while comparing.
For the above example I should:
clientLog
& return true if whole word matches.(in this example it should return false as source has clientLogin
).I am trying to use RegEx to achieve this
var regEx = new RegExp(k); // k is the search text
if(regEx.test(classNames)){....
Above code is inside jQuery.each,k is the key of the object which is being iterated.I did not figure out how to omit the '.' but read somewhere to implement Word Boundries for the exact match.
Please suggest.
thanks
Upvotes: 0
Views: 1182
Reputation: 91
In JavaScript, you can strip text with the substring()
method like this:
var str = "Hello World!";
var sub_str = str.substring(1, str.length);
In substring(x, y)
, x is the starting index of the new string, y is the ending index. The indecies in JavaScript start at 0, so we have to use the next index to omit the first character in the string.
You can also read it up here on W3Schools.
You can search RegEx patterns in strings like this:
var str = "Hello World!";
var pos = str.search(/World/); // Attention: No quotes here!
pos
equals the index of the first match of the given expression. If your expression did not match your string, then pos
will equal -1
.
Note, that str.search(/World/);
is basicly the same as str.search(new RegExp("World"));
You can also read it up here on W3Schools.
To check, if your string contains that classname, you could do this:
var str = "classname1 classname2 classname3";
var search_str = ".classname2";
if(str.search(new RegExp("\\b(" + search_str.substring(1, search_str.length) + ")\\b")) > -1){
// classname found
} else {
//classname not found
}
Upvotes: 2
Reputation: 34628
Try this:
var
source = 'text clientLogin padding float',
search = '.clientLog',
pattern = '\\b'+search.replace(/^\./, '')+'\\b',
result = new RegExp(pattern).test(source);
Notes:
\b
). This helps ensure that "login" is not considered a valid match for "log", for example, like in your case.\\b
) is necessary as we're building our pattern as a string - this is necessary for dynamic patterns fed to the RegExp
constructor.Upvotes: 2