这可能很简单,但我不太擅长 javascript,尤其是正则表达式。我知道有一种方法可以使用 .substr()
或 .substring()
获取子字符串。如果我知道 url 字符串的索引位置但文本是从数据库加载的,这对我来说很容易。
示例 html:
<div>
<p>Some text text text text http://stackoverflow.com text text
text http://google.com text text text.
</p>
</div>
我希望每个 url 字符串作为输出插入一个数组。
var mystrings = new Array
var text = $('p').text();
var url = text.substr()//don't know the logic here
mystrings.push(url);
//output
mystrings[0] == 'http://stackoverflow.com'
mystrings[1] == 'http://google.com'
我也找到了这个正则表达式,但我不知道如何合并它:
var regexp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
最佳答案
检查这个 JSFiddle .使用 RegExp.exec()
在您的 text
变量上执行正则表达式。由于表达式上有 g
全局修饰符,while
循环将遍历字符串中每个匹配的 URL。
var mystrings = new Array;
var text = $('p').text();
var regexp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
while (matches = regexp.exec(text))
{
mystrings.push(matches[0]);
}
console.log(mystrings);
// ["http://stackoverflow.com", "http://google.com"]
关于javascript - 提取元素内的所有有效 URL 字符串 (JavaScript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21127445/