-3

I'm programming a social media engine and I'd like to use jQuery to automatically wrap all http and https links into an <a> element.

This is what I've gotten to after a lot of Google searching:

$('*').each(function test() {
    var str = $(this);
    if(str.match("^http")) {
        str.wrap("<a></a>");
    }
});

But when I run the code, I get the following error in the log.

TypeError: str.match is not a function [Learn More]

What would be the best way to go about doing this?

  • 1
    `$(this)` would be an element not a text. – zerkms Oct 08 '18 at 21:57
  • 4
    `str` is not a string. It's a jQuery object. Did you check https://api.jquery.com/ to see if `match()` is an existing method? – Taplar Oct 08 '18 at 21:57
  • 1
    Can you show a representative sample of the HTML you're working with, including examples of the text (as an input/'before') and show the result you're hoping to create (the output/'after')? – David Thomas Oct 08 '18 at 22:04

2 Answers2

1

As others have mentioned, JavaScript's match() operates on a string and $(this) is a jQuery object, not a string. See What's the difference between '$(this)' and 'this'?

I suggest testing match() against the text() content of the element.
If it starts with "http", wrap the element with an <a> with its href set to the text content.

$('span,p').each(function() {
  var $str = $(this);
  var text = $str.text();
  if (text.match("^http")) {
    var $link = $("<a>", {
      'href': text
    });
    $str.wrap($link);
  }
});
span,
p {
  display: block;
  margin: 0 0 .5em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<span>http://google.com</span>
<span>file://host/path</span>
<p>https://stackoverflow.com</p>
<p>Something Else</p>
showdev
  • 28,454
  • 37
  • 55
  • 73
0

Admittedly wasn't specific with my question the first time around, but I managed to get my answer regardless.

$('.content').html($('.content').html().replace(/@([^\s]+)/g,'<a href="$1">@$1</a>'));

This will wrap all code starting with "@" in an element.