当前位置:  开发笔记 > 编程语言 > 正文

如何使用jquery从链接中选择href属性?

如何解决《如何使用jquery从链接中选择href属性?》经验,为你挑选了1个好方法。

我有一个像这样的字符串:

var str = 'anything ...www.example.com/clas  anything';

我想要这个输出:

var newstr: 'anything http://www.example.com/classname/methodname/arg1/arg2 anything';

我怎样才能做到这一点?实际上我几乎可以使用多个来做到这一点str_replace().但是我想知道如何使用正则表达式来做到这一点?

str.str_replace('', '');
str.str_replace('  ', '');

// output:
anything http://www.example.com/classname/methodname/arg1/arg2...www.example.com/clas anything

好吧,如你所见,我无法删除...www.example.com/clas我的输出.

注意: anything在示例中可以是任何单词/句子.顺便说一句,实际上有波斯人物.


Edit1:这是一个例子:

我想替换这个:

This  ... www.example.com/clas  is very good.

有了这个:

This www.example.com/classname/methodname/arg1/arg2/ is very good.

Edit2:我还需要该链接的值.像这样的模式:

[LinkName](LinkAddress)

注意:如果该链接的值不是"无标题",我想创建上面的模式.

例1:

var str = 'anything website name  anything';

我要这个:

var newstr: 'anything [website name](http://www.example.com/classname/methodname/arg1/arg2 anything)';

例2:

var str = 'anything untitled  anything';

我要这个:

var newstr: 'anything http://www.example.com/classname/methodname/arg1/arg2 anything';

A. Wolff.. 6

你可以str在DOM元素中包装,找到任何锚标记,用它自己的href属性替换它,然后返回新的字符串:

var newStr = $('
', {html: str}).find("a").replaceWith(function(){ return $(this).attr('href'); // this.href would give absolute path }).end().text();

var str = 'anything ...www.example.com/clas  anything';

var newStr = $('
', {html: str}).find("a").replaceWith(function(){ return $(this).attr('href'); }).end().text(); console.log(newStr); $('body').append(newStr);



1> A. Wolff..:

你可以str在DOM元素中包装,找到任何锚标记,用它自己的href属性替换它,然后返回新的字符串:

var newStr = $('
', {html: str}).find("a").replaceWith(function(){ return $(this).attr('href'); // this.href would give absolute path }).end().text();

var str = 'anything ...www.example.com/clas  anything';

var newStr = $('
', {html: str}).find("a").replaceWith(function(){ return $(this).attr('href'); }).end().text(); console.log(newStr); $('body').append(newStr);
推荐阅读
ERIK又
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有