Nitin Gandhi
Nitin Gandhi

Reputation: 25

Convert Text in an Input to show as href links using comma split in javascript/jquery

I am trying to split text with comma and show them as links. I am converting them as as text but don't know how to convert them into links. I am using this code.

$('.tags').keyup(function() {
var ref = $('.tags').val();
var str_array = ref.split(',');

for(var i = 0; i < str_array.length; i++) {
   // Trim the excess whitespace.
   str_array[i] = str_array[i].replace(/^\s*/, "").replace(/\s*$/, "");
   // Add additional code here, such as:
$('.tag').html($(this).val());
}
});

What I am Getting is

<span class="tag">hello, world</span>

what I want is

<span class="tag"><a href="hello">hello</a>, <a href="world">world</a></span>

Upvotes: 0

Views: 671

Answers (3)

Tom Marienfeld
Tom Marienfeld

Reputation: 716

This solution is done with pure JS. No need for JQuery

var tags = document.getElementById("tags");
tags.addEventListener("keyup", convert);

function convert() {
let tag = document.getElementById('tag');
tag.innerHTML = "";
let str = tags.value;
let res = str.split(",");
res.forEach(function(element, idx, array) {
let comma;
idx === array.length - 1 ? comma = '' : comma = ' , ';
let trimmedElement = element.trim();
tag.innerHTML += '<a href="'+ trimmedElement +'">'+ trimmedElement +'</a>'+ comma ;  
});
}
<input type="text" id="tags">

<span id="tag"></span>

Upvotes: 1

Ishpreet
Ishpreet

Reputation: 667

You can do as follows in jQuery:

var ref = $('.tags').val();
var str_array = ref.split(',');
var tagLinks = '';

for(var i = 0; i < str_array.length; i++) {
   // Trim the excess whitespace.
   str_array[i] = str_array[i].replace(/^\s*/, "").replace(/\s*$/, "");
   tagLinks += '<a href="'+str_array[i]+'">'+str_array[i]+'</a>, ';
}

tagLinks = tagLinks.slice(0, -2);

$('.tag').html(tagLinks);

Upvotes: 1

Mahdi Amiri
Mahdi Amiri

Reputation: 339

With jQuery:

// Element Selector
let selector = $(".tag");

// Get Text
let text = selector.text();

// Remove extra characters
text = text.replace(/[^a-zA-Z ]/ig, '');

// Convert my text to array
let tags = text.split(" ");

// Empty the element
selector.html('');

// Append Tags
tags.forEach(function(tag){
    selector.append(`<a href="${tag}">${tag}</a> &nbsp;`)
});

Upvotes: 0

Related Questions