2

How can I replace 'http://' or 'https://' from a text added with javascript?

I am also interested in regex solutions.

Here is what I made so far:

JSFIDDLE

HTML:

<div class="string"></div>

JS:

$text = $('.string').text("http://www.text.com");

if ($text.startsWith('http://')) {
    $text.replace('http://','');
}
else if ($text.startsWith('https://')) {
    $text.replace('https://','');
}
Valip
  • 4,440
  • 19
  • 79
  • 150

3 Answers3

2

The issue stands in what $text contain. it contains the element, not the text!

try this code:

$text.html($text.html().replace('http',''));

update

editing and simplifying your code it would be:

$text = $('.string').text("http://www.text.com");

$text.text($text.text().replace('https://','').replace('http://',''));

update (again)

You can also use a regex to do it.

$text.text( $text.text().replace(/http(s?):\/\//g,'') );

Plaease check this updated fiddle.

morels
  • 2,095
  • 17
  • 24
1

Check this updated fiddle

var $text = $('.string').text("http://www.text.com");

if ($text.text().indexOf('http://') != -1) 
{
    $text.text( $text.text().replace('http://','') );
}
else if ($text.text().indexOf('https://') != -1) {
    $text.text( $text.text().replace('https://','') );
}
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
0

Try this one:

var $text = $('.string').text("http://www.text.com");

$text.text($text.text().split('://')[1]);

This code will remove any protocol from your URL.

morels
  • 2,095
  • 17
  • 24
Satish Kumar sonker
  • 1,250
  • 8
  • 15