0

I have a string

<a href="http://google.com">http://google.com</a> This is a good page

I try to get only http://google.com but i can't.

Please give me some solution to do it, thank you.

guari
  • 3,715
  • 3
  • 28
  • 25
thanhhuy12thh
  • 41
  • 1
  • 6
  • you mean you want value of href attribute? – Nitesh May 11 '17 at 04:25
  • you want to get it from where, `href` or inside the ``? – JJJ May 11 '17 at 04:26
  • Get google.com between – thanhhuy12thh May 11 '17 at 04:29
  • I have two questions. First, You say this is a string, but I'm not sure that's what you really mean. Are you running jQuery on a normal webpage, and is this text in the webpage? (If so, this is the DOM, not a regular string.) Second, do you want to keep the text "This is a good page" in your output? – Jack Taylor May 11 '17 at 04:31
  • 1. I' running Jquery on my page, i get this text from Json, it is a string from json. 2. Yes, i want to keep this text. – thanhhuy12thh May 11 '17 at 04:36

4 Answers4

1

Or if you want the jQuery version:

let string = $('a').attr('href');
Darkisa
  • 1,899
  • 3
  • 20
  • 40
1

Try this

Get the value :

$('a').attr('href');

Replace the link :

$("a").attr('href','javascript:void(0)');

Get the text :

$("a").text();
Bachcha Singh
  • 3,850
  • 3
  • 24
  • 38
0

First, you have to convert the string to DOM elements, using one of the techniques in this question. (I use the accepted answer, but you should choose the one that matches your use-case the best.)

var str = '<a href="http://google.com">http://google.com</a> This is a good page';
var div = document.createElement('div');
div.innerHTML = str;

You can then manipulate the elements using normal JavaScript DOM methods. Here I do it with jQuery:

$(div).text(); // "http://google.com This is a good page"
$('a', div).attr('href'); // "http://google.com"

A final note: beware when working with with HTML strings! If you put untrusted HTML into your page's DOM, you will create a cross-site scripting vulnerability. If you control the source of the JSON data, then it would be a good idea to just send the strings you need, instead of HTML strings - that way you can avoid parsing the HTML altogether.

Community
  • 1
  • 1
Jack Taylor
  • 5,588
  • 19
  • 35
-2

Try following js code,

following code is working but not recommended,

$('a').attr('href');


$("a").attr('href','javascript:void(0)');

Get the text :

$("a").text()
Prabhat Sinha
  • 1,500
  • 20
  • 32
  • Welcome, @thanhhuy12thh – Prabhat Sinha May 11 '17 at 05:14
  • 1
    Depending on where the JSON data comes from, and how you intend to use the string, this answer could be dangerous. It might lead to a [cross-site scripting](https://en.wikipedia.org/wiki/Cross-site_scripting) vulnerability. Instead, you should parse the HTML with a proper HTML parser, or if you can change the code that is generating the JSON, adjust the JSON format so that you don't have to parse any HTML. – Jack Taylor May 11 '17 at 06:28