Mukesh Kumar
Mukesh Kumar

Reputation: 43

Append New String at position of another string

I have two variables and need to insert string b into string a at the point after href.

var a = '<a href="http://pix6.agoda.net/">Image Credit</a>';
var b = 'rel="nofollow noreferrer noopener"';

The result I'm looking for is

<a href="http://pix6.agoda.net/" rel="nofollow noreferrer noopener">Image Credit</a>

How can I do this with JavaScript?

Upvotes: 2

Views: 81

Answers (4)

abhay
abhay

Reputation: 642

One more way

var a = '<a href ="http://pix6.agoda.net/">Image Credit</>'
var b = 'rel="nofollow noreferrer noopener">'
var d = a.split('>')[0]
var e = a.split('>')[1]
var x = d +' '+b +e 
console.warn(x)

Upvotes: 2

Eriks Klotins
Eriks Klotins

Reputation: 4180

To combine the strings you can use

 a.slice(0,a.indexOf(">")) + b + a.slice(a.indexOf(">"))

however, you should not do that to create a DOM node

Upvotes: 2

Quentin
Quentin

Reputation: 943599

As a rule of thumb, trying to manipulate HTML by ripping apart and gluing strings together is a nasty, error-prone business.

Use DOM manipulation instead.

var html = '<a href="http://pix6.agoda.net/">Image Credit</a>';

const domparser = new DOMParser();
const doc = domparser.parseFromString(`<div>${html}</div>`, "text/html");
const link = doc.querySelector("a");
link.setAttribute("rel", "nofollow noreferrer noopener");
const output = doc.querySelector("div").innerHTML;
console.log(output);

Upvotes: 2

Alessio Cantarella
Alessio Cantarella

Reputation: 5201

You could insert the b string after the href using the JavaScript indexOf function, i.e.:

let a = '<a href="http://pix6.agoda.net/">Image Credit</a>';
let b = 'rel="nofollow noreferrer noopener"';
let h = 'href="';
let i = a.indexOf(h);
if (i > -1) {
  let j = a.indexOf('"', i + h.length);
  if (j > -1) {
    let c = a.substr(0, j + 1) + ' ' + b + a.substr(j + 1);
    console.log(c);
  }
}

Upvotes: 2

Related Questions