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
答案 0 :(得分:2)
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.答案 1 :(得分:2)
在JavaScript中,您可以使用substring()
方法删除文本,如下所示:
var str = "Hello World!";
var sub_str = str.substring(1, str.length);
在substring(x, y)
中,x是新字符串的起始索引,y是结束索引。 JavaScript中的indecies从0开始,因此我们必须使用下一个索引来省略字符串中的第一个字符。
您也可以阅读here on W3Schools。
您可以在以下字符串中搜索RegEx模式:
var str = "Hello World!";
var pos = str.search(/World/); // Attention: No quotes here!
pos
等于给定表达式的第一个匹配的索引。如果您的表达式与您的字符串不匹配,则pos
将等于-1
。
请注意,str.search(/World/);
与str.search(new RegExp("World"));
您也可以阅读here on W3Schools。
要检查,如果您的字符串包含该类名,您可以这样做:
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
}