Regular expression to test exact word with a trailing dot

时间:2016-08-31 12:24:16

标签: javascript regex

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:

  1. Get the part of search after '.'(dot)
  2. Check the source for the search text i.e 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

2 个答案:

答案 0 :(得分:2)

Try this:

var
source = 'text clientLogin padding float',
search = '.clientLog',
pattern = '\\b'+search.replace(/^\./, '')+'\\b',
result = new RegExp(pattern).test(source);

Notes:

  • We strip off the leading '.' from the search string while building the pattern
  • We use word boundary markers (\b). This helps ensure that "login" is not considered a valid match for "log", for example, like in your case.
  • The double-escaping (\\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
}