使用JavaScript中的正则表达式从锚标记字符串中提取内部文本 [英] Extract inner text from anchor tag string using a regular expression in JavaScript

查看:67
本文介绍了使用JavaScript中的正则表达式从锚标记字符串中提取内部文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是angular js的新手.我有regex,它获取了所有的anchor tags.我的前任是

I am new to angular js . I have regex which gets all the anchor tags. My reg ex is

/<a[^>]*>([^<]+)<\/a>/g

我在这里使用match函数,

var str =  '<a href="mailto:abc.jagadale@gmail.com" style="color:inherit;text-decoration:inherit">abc.jagadale@gmail.com</a>'

所以现在我正在使用

var value = str.match(/<a[^>]*>([^<]+)<\/a>/g);

因此,在这里我期望输出为abc.jagadale@gmail.com,但是我得到的字符串与input string完全相同.有人可以帮我吗?预先感谢.

So, Here I am expecting the output to be abc.jagadale@gmail.com , But I am getting the exact same string as a input string . can any one please help me with this ? Thanks in advance.

推荐答案

您为什么要重新发明轮子?

您正在尝试使用正则表达式解析HTML字符串,这将是一项非常复杂的任务,只需使用DOM或jQuery来获取链接内容,它们就是为此而设计的.

You are trying to parse the HTML string with a regex it will be a very complicated task, just use DOM or jQuery to get the links contents, they are made for this.

  • 将HTML字符串作为jQuery/DOM元素的HTML.

  • Put the HTML string as the HTML of a jQuery/DOM element.

然后获取此创建的DOM元素以获取所有a元素 在其中,然后将它们的内容返回到数组中.

Then fetch this created DOM element to get all the a elements inside it and return their contents in an array.

这应该是您的代码:

var str = '<a href="mailto:abc.jagadale@gmail.com" style="color:inherit;text-decoration:inherit">abc.jagadale@gmail.com</a>';

var results = [];
$("<div></div>").html(str).find("a").each(function(l) {
  results.push($(this).text());
});

演示:

var str = '<a href="mailto:abc.jagadale@gmail.com" style="color:inherit;text-decoration:inherit">abc.jagadale@gmail.com</a>';

var results = [];
$("<div></div>").html(str).find("a").each(function(l) {
  results.push($(this).text());
});
console.log(results);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

这篇关于使用JavaScript中的正则表达式从锚标记字符串中提取内部文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆