Brandon Ellis
Brandon Ellis

Reputation: 23

How do I match a single word in Javascript Regex?

I just want to match one word (\w+) after a pattern in javascript.

Here is my simple test code:

(new RegExp("apple:\w+")).test("apple:asdf");

However, I am being told by javascript that the pattern does not match. This goes against pretty much everything I'm used to about regex matching. Even when I tested it on regex101.com I got a match.

What is the convention used for matching a word?

Upvotes: 2

Views: 14028

Answers (3)

tyzion
tyzion

Reputation: 131

I'd like to make the Regex a little more general. And also, since I read match in the question, I thought some other people will look for match expression and not test like I did.

In my case I had to match the word right after a pattern similar to yours (number:). Plus there can be multiple whitespaces after the colons

So, my answer is this, if you need to actually match a word, and not test:

'number: 5646 bksfdg df34'.match(/number:\s*([0-9]+)/)

In this way, /s* says to ignore all the whitespaces until the next pattern and ([0-9]+) is the matching group of all the subsequent numbers after the "number:" pattern+

If you need to match a word, as @raina77ow suggested, you could use ([a-z]+) in my regexp

I know this answers more to the title than specifically to the OP, but as I told you I hope this can help others who came here looking for a matching and not testing Regex function

Upvotes: 0

raina77ow
raina77ow

Reputation: 106385

First, you need to escape that slash inside your string literal, otherwise it'll be just lost:

const slashIsLost = "apple:\w+";
console.log(slashIsLost); // apple:w+

const slashIsEscaped = "apple:\\w+";
console.log(slashIsEscaped ); // apple:\w+

Second, you need to remember that \w matches both letters, digits and _ character. So you might better use [A-Za-z] character class instead - or just bite the first pair and make RegExp case-insensitive with i flag.

As a sidenote, it's really not clear why don't you just use RegExp literal here:

/apple:[a-z]+/i.test('apple:asdf')

Upvotes: 4

adnauseam
adnauseam

Reputation: 815

Your thought is good, but you need to escape your backslashes when using the RegEx constructor. MDN recommends:

Using the constructor function provides runtime compilation of the regular expression. Use the constructor function when you know the regular expression pattern will be changing, or you don't know the pattern and are getting it from another source, such as user input.

An alternative is the regular expression literal syntax:

Regular expression literals provide compilation of the regular expression when the script is loaded. If the regular expression remains constant, using this can improve performance.

Try this code:

const re = /apple:\w+/
const str = "apple"
re.test(str)

Check out the MDN docs

Upvotes: 0

Related Questions