0

How to replace all the occurrences of

<a href="http://localhost:4000/disease/description/{a random text}"></a>

So here I want to add target="_bank" to all the anchor tags which has the url 'http://localhost:4000/disease/description/*'.I put start because it indicates a random text.

I tried like this

var text = data.replace(/ href="http://localhost:4000/disease/description/*/g,'href="http://localhost:4000/disease/description/* target="_blank"');

But this doesnt work.Can anyone please suggest me help.Thanks.

4 Answers 4

1

You could use document.querySelectorAll() to grab anchors starting with that url. From there, loop through them and set the target attribute via setAttribute:

const anchors = document.querySelectorAll('a[href^="http://localhost:4000/disease/description"]');

Array.from(anchors).forEach(a => a.setAttribute('target', '_blank'));
<a href="http://localhost:4000/disease/description">Disease Description 1</a>
<a href="http://localhost:4000/disease/description">Disease Description 2</a>
<a href="http://localhost:4000/disease/description">Disease Description 3</a>

<a href="">Dummy Link</a>
<a href="">Dummy Link</a>
<a href="">Dummy Link</a>

Sign up to request clarification or add additional context in comments.

Comments

0

Like this.

I don't know why but this JsFiddle Code doesn't work here, but if you run it on your IDE, it works properly.

var a = document.querySelector('a');
a.href = 'https://google.com';
a.target = '_blank';
<a>Google</a>

Comments

0

What about

var data='<a href="http://localhost:4000/disease/description/{a random text}"></a>'

var c = data.replace('<a','<a target="_bank"')

console.log(c)

Comments

0

for example, in your case:

data ='<a href="http://localhost:4000/disease/description/{a random text}"></a>';
var text = data.replace(/href="http:\/\/localhost:4000\/disease\/description\/([^"]*)"/g,'href="http://localhost:4000/disease/description/$1" target="_blank"');
console.log( text );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.