开发者

Javascript url regex returns a comma at the end of the url, any way to fix this?

I have a regex to match URLs. It matches very well for anything that is written with www. or starts with http:// but, it adds a comma to any matched urls. For example when I take the value from a textarea and match it up and then replace the textarea value with the matched value it places a comma at the end of the url:

var urlexp = /[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi;

$('button').click(function(){

var text = $('.textar开发者_StackOverflow社区ea').val();
if((text.match(urlexp))) {

var urlMatch = urlexp.exec(text);

$('.textarea').val(urlMatch);
}
});

When I type http://www.google.com and click the button http://www.google.com is replaced with http://www.google.com, which is causing a problem, is there anyway to fix this?


the problem isn't with the regex, it's with you setting the val.

try:

$('.textarea').val(urlMatch[0]);


How about using match:

var textarea = $('.textarea');
var text = textarea.val();
var match = text.match(urlexp);

if (match) {
    textarea.val(match[0]);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜