简体   繁体   中英

JavaScript regex (missing '/'), how do I fix this?

I have simple script, I want to get my images and then divide them by commas. However I cannot get image links inside [gallery] tags since I get Uncaught SyntaxError: Invalid regular expression: missing / .

Can someone please take a look and show me where is the problem in my RegEx code?

HTML

<textarea>
abc
[gallery]/content/img/upload/img-2012.03.19.-634677727044317051.jpg, /content/img/upload/img-2012.03.19.-634677727046997204.jpg, /content/img/upload/img-2012.03.19.-634677727049487347.jpg, /content/img/upload/img-2012.03.19.-634677727051787478.jpg, /content/img/upload/img-2012.03.19.-634677727054137613.jpg[/gallery]
def
</textarea>​

JavaScript

$(function(){
    var text = $('textarea').val();
    var re = /\[gallery\]([^}]+)[/gallery\]/g;
    var gallery = re.exec(text);
    alert(gallery);
});​

Fiddle : http://jsfiddle.net/BcFsg/

yep, the problem is you missed one escape character

var re = /\[gallery\]([^}]+)\[\/gallery\]/g;
//                          |
//                       [ HERE ]

jsfiddle here http://jsfiddle.net/BcFsg/1/

你需要躲避/由eriting在正则表达式的中间\\/

see the updated fiddle... I do not know why but it seems you do not have to escape the closing ]

EDIT: gave wrong output (all squared brackets need to be escaped)... updated fiddle EDIT 2: updated fiddle to only alert the list of images

fiddle

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