简体   繁体   中英

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 ?

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, _ .

You should escape | char:

/\|Facebook/g

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM