所以我在解析字符串时遇到了一些麻烦。我需要解析" images / foo / bar / anotherfoo / imageId" 来自
"url(http://some/folder/path/images/foo/bar/anotherfoo/imageId)"
我已经尝试过使用regEx,但对于这么大且特定的子字符串,我对它们知之甚少。任何帮助都会有所帮助,谢谢。
答案 0 :(得分:2)
对于此特定字符串,如果您坚持使用正则表达式,则可以使用以下内容:
var s = 'url(http://some/folder/path/images/foo/bar/anotherfoo/imageId)';
s = s.replace(/.*(?=images)|\W$/g, '');
console.log(s); //=> 'images/foo/bar/anotherfoo/imageId'
或使用字符串match()
方法..
var s = 'url(http://some/folder/path/images/foo/bar/anotherfoo/imageId)',
r = s.match(/images[^)]*/);
console.log(r[0]); //=> 'images/foo/bar/anotherfoo/imageId'
答案 1 :(得分:0)
所以我看到的是你有一些基本网址http://some/folder/path/
,包裹着一个CSS url()
。请参阅以下内容:
var base_url = 'http://some/folder/path/';
var search = 'url(http://some/folder/path/images/foo/bar/anotherfoo/imageId)';
// That replace is adding back slashes to the base_url so that the regex expression
// doesn't get confused. You could also just remove it entirely, but since you wanted
// a regex based expression...
var pattern = '/url(' + base_url.replace(/\//g, '\\/') + '([\w\/]+)\))/i';
if(regex.test(input))
{
var matches = input.match(regex);
for(var match in matches)
{
alert(matches[match]);
}
}
else
{
alert("No matches found!");
}
如果您想了解有关正则表达式的更多信息,我建议您转到RegexOne进行教程和练习 - 从中学习。