tobiger
tobiger

Reputation: 103

Regular expression in javascript ignores newline

I was wondering why the following regular expression results to TRUE:

var users = "TEST\nTEST2";
var user  = "TEST5"
var position = users.search( user + "\n|$"); // result: 10

I want to search a user in users. Can somebody please explain me the result?

Upvotes: 1

Views: 70

Answers (2)

sp00m
sp00m

Reputation: 48807

Your regex ends to TEST5\n|$, which means "either TEST5\n or the end of the string":

Regular expression visualization

Debuggex Demo

TEST5\n is not found, but the end of the string is, at index 10 (your string has 10 chars).

I guess you're looking for user + "(\\n|$)":

Regular expression visualization

Debuggex Demo

Note that I escaped the backslash, since in a string literal. It won't change the result though, but it's the regex-way to write a newline.

Upvotes: 3

garyh
garyh

Reputation: 2852

You could use a positive lookahead

user + "(?=\\n|$)"

This means user which is followed by either \n or $

Upvotes: 0

Related Questions