Open In App

JavaScript string anchor() Method

Last Updated : 16 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

The JavaScript anchor() method creates an anchor element that is used as a hypertext target that means when you use the anchor method in JavaScript the anchor method returns <a> elements with string and also returns “anchorname” as the value of “name” attribute like this:

<a name=anchorname>string</a>

Syntax:

 string.anchor(anchorname)

Note: This method has been DEPRECATED and is no longer recommended.

Parameters:

This method accepts a single parameter.

  • anchorname: The name of the anchor.

Return Value:

The anchor() method returns the string with <a> element.

Example 1: This example shows the basic use of the anchor tag in Javascript.

let str = "GFG";
console.log(str.anchor("anchorname"));

Output
<a name="anchorname">GFG</a>

Example 2: This example shows you how to use anchor() method.

let str = "GeeksForGeeks";
console.log(str.anchor("anchorname"));

Output
<a name="anchorname">GeeksForGeeks</a>

Supported Browsers:

  • Chrome 1
  • Edge 12
  • Firefox 1
  • Opera 3
  • Safari 1

JavaScript string anchor() Method – FAQs

What does the anchor() method do in JavaScript?

The anchor() method is used to create an HTML anchor (<a>) tag with a specified URL and text within a string. It was commonly used in early JavaScript for dynamically creating links in HTML documents.

Is the anchor() method still recommended for use?

No, the anchor() method is considered outdated. Modern web development practices use frameworks like React or Vue.js for dynamic content rendering and prefer using <a> tags directly in HTML or through JavaScript for better maintainability and performance.

Can anchor() handle attributes like target or rel in the generated anchor tag?

No, the anchor() method in its basic form does not support adding attributes like target or rel to the generated <a> tag. It only creates a simple <a> tag with the provided URL and text.

Does anchor() affect the original string?

No, the anchor() method returns a new string with the HTML anchor tag embedded. It does not modify the original string.

When was the anchor() method introduced in JavaScript?

The anchor() method has been part of JavaScript since its early versions, primarily used in conjunction with HTML 4 to dynamically create links within web pages.

We have a complete list of Javascript string methods, to check those please go through the Javascript String Complete Reference article.


Next Article

Similar Reads

three90RightbarBannerImg