如何从链接中提取href属性并创建一个特定的模式?
我用两个例子解释我的问题:
例1:
当前字符串:
var str = 'anything untitled anything'; // ^ link-name
我想要这个字符串:
var newstr = 'anything https://stackoverflow.com/questions/34415399/how-to-extract-href-attribute-from-link-and-create-a-specific-pattern-of-that/www.google.com anything';
例2:
当前字符串:
var str = 'anything any thing else anything'; // ^ link-name
我想要这个字符串:
var str = 'anything [any thing else](https://stackoverflow.com/questions/34415399/how-to-extract-href-attribute-from-link-and-create-a-specific-pattern-of-that/www.google.com) anything';
正如您在上面的两个示例中所看到的, untitled
是一个关键字。 我想如果link-name是untitled
,那么创建一个常规的URL,但如果不是,则创建一个基于模式的URL。
注意: pattern = [LinkName](LinkAddress)
我怎样才能做到这一点?
这也是我尝试过的:
var newStr = $('', {html: str}).find("a").replaceWith(function(){ return $(this).attr('href'); // this.href would give absolute path }).end().text();
我的代码从所有类型的链接创建一个常规URL。 如何添加该条件(检查链接名称是否为untitled
) ?
我不明白。 你做的是对的。 以下是您的解决方案:
$(function () { var str = 'anything untitled anything'; var newStr = $('', {html: str}).find("a").replaceWith(function(){ return ($(this).text().trim().toLowerCase() == 'untitled') ? $(this).attr('href') : "[" + $(this).text() + "](" + $(this).attr('href') + ")"; }).end().text(); $("body").append(newStr + "
"); str = 'anything any thing else anything'; newStr = $('', {html: str}).find("a").replaceWith(function(){ return ($(this).text().trim().toLowerCase() == 'untitled') ? $(this).attr('href') : "[" + $(this).text() + "](" + $(this).attr('href') + ")"; }).end().text(); $("body").append(newStr); });
您只需要检查元素的文本内容:
var newStr = $('', { html: str }).find("a").replaceWith(function() { var href = this.getAttribute('href'), text = this.textContent ; return text === 'untitled' ? href : "[" + text + "](" + href + ")"; }).end().text();