Pawan Nogariya
Pawan Nogariya

Reputation: 8950

Regular expression to get the string including the starting character

I have a string like this

var str="|Text|Facebook|Twitter|";

I am trying to get any one of the word with its preceding pipe sign so something like

|Text or |Facebook or |Twitter

I thought of below two patterns but they didn't work

/|Facebook/g  //returned nothing
/^|Facebook/g // returned "Facebook" but I want "|Facebook"

What should I use to get |Facebook?

Upvotes: 1

Views: 38

Answers (2)

falsetru
falsetru

Reputation: 368894

The pipe is special character in a regular expression. A|B matches A or B.

You have to escape the pipe to match | literally.

var str = '|Text|Facebook|Twitter|'
str.match(/\|\w+/g) // => ["|Text", "|Facebook", "|Twitter"]

\w matches any alphabet, digit, _.

Upvotes: 3

antyrat
antyrat

Reputation: 27765

You should escape | char:

/\|Facebook/g

Upvotes: 1

Related Questions