techie_28
techie_28

Reputation: 2133

Regular expression to test exact word with a trailing dot

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

Upvotes: 0

Views: 1182

Answers (2)

RicoBrassers
RicoBrassers

Reputation: 91

Stripping text

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.


Regular Expressions

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

Mitya
Mitya

Reputation: 34628

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.

Upvotes: 2

Related Questions