totn JavaScript

JavaScript: String anchor() method

This JavaScript tutorial explains how to use the string method called anchor() with syntax and examples.

Description

In JavaScript, anchor() is a string method that is used to create the HTML <a> element (or anchor). Because the anchor() method is a method of the String object, it must be invoked through a particular instance of the String class.

Syntax

In JavaScript, the syntax for the anchor() method is:

string.anchor(anchor_name);

Parameters or Arguments

anchor_name
It is a string value that will be used as the name attribute for the <a> element.

Returns

The anchor() method returns a string containing an <a> element. The value of string is enclosed in <a> and </a> tags as the hyperlink text and the value of the anchor_name parameter is used as the name attribute for the <a> element.

Note

  • The anchor() method does not change the value of the original string.

Example

Let's take a look at an example of how to use the anchor() method in JavaScript.

For example:

var totn_string = 'TechOnTheNet';

console.log(totn_string.anchor('website'));

In this example, we have declared a variable called totn_string that is assigned the string value of 'TechOnTheNet'. We have then invoked the anchor() method of the totn_string variable to return a string that contains the HTML anchor.

We have written the output of the anchor() method to the web browser console log, for demonstration purposes, to show what the anchor() method returns.

The following will be output to the web browser console log:

<a name="website">TechOnTheNet</a>

As you can see, the anchor() method created a string that contains an <a> element. The value of the totn_string variable (which is 'TechOnTheNet') is enclosed within the <a> and </a> tags. The string value of 'website' that was passed into the anchor() method as a parameter is used as the name attribute for the <a> element.