Match entire string

Which regular expression (in JavaScript, if that matters) matches only whether the text matches an exact match? That is, at the other end of the line there should be no additional characters.

For example, if I try to match for abc , then 1abc1 , 1abc and abc1 do not match.

+135
javascript regex
Jun 09 2018-11-11T00:
source share
3 answers

Use start and end separators: ^abc$

+253
Jun 09 2018-11-11T00:
source share

It depends. You could

 string.match(/^abc$/) 

But this does not correspond to the following line: 'the first 3 letters of the alphabet are abc. Not abc123'

I think you want to use \ b (word boundaries)

 var str = 'the first 3 letters of the alphabet are abc. not abc123'; var pat = /\b(abc)\b/g; console.log(str.match(pat)); 

Real-time example: http://jsfiddle.net/uu5VJ/

If the first solution works for you, I would advise against using it.

That means you might have something like the following:

 var strs = ['abc', 'abc1', 'abc2'] for (var i = 0; i < strs.length; i++) { if (strs[i] == 'abc') { //do something } else { //do something else } } 

While you can use

 if (str[i].match(/^abc$/g)) { //do something } 

This will be significantly more resource intensive. For me, the general rule is that a conditional expression is used for simple string comparisons, since a more dynamic pattern uses a regular expression.

more info about regex's JavaScript: https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions

+35
Jun 09 '11 at 20:26
source share

"^" To start the string "$" to end. For example.:

 var re = /^abc$/; 

Will match "abc", but not "1abc" or "abc1". You can find out more at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

+13
Jun 09 2018-11-11T00:
source share



All Articles