JavaScript String anchor() Method

Beginner
⏱️ 9 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Deprecated

What You’ll Learn

String.prototype.anchor() is a deprecated HTML wrapper method (same API as MDN String.prototype.anchor()). It returns a string that wraps your text in an <a name="..."> tag. Learn what it builds, why that markup is obsolete, and how to replace it with document.createElement().

anchor()

Instance method

Wraps a string in <a name> HTML markup you can inspect and learn from.

Returns

HTML string

Produces markup text only — not a live DOM node you can append.

Deprecated

Legacy only

Kept for backward compatibility. Recognize it, but avoid it in new code.

name

Single param

Coerced to a string and placed in the name attribute; quotes are escaped.

Immutable

No mutation

Returns a brand-new string — the original text is never changed.

createElement

Modern swap

Build real <a> elements with id and href instead.

Introduction

Early JavaScript shipped several HTML wrapper methods that turned a string into a markup snippet — bold(), italics(), anchor(), and more. They made it quick to build HTML for innerHTML.

Today those wrappers are deprecated. anchor() still runs in browsers for compatibility, but the markup it builds is no longer valid HTML.

Why it’s deprecated?

The name attribute is no longer allowed on <a> elements, so the string anchor() produces is obsolete markup.

Key Highlights

Returns HTML Text

Builds an <a name> string, not a live DOM node.

String Immutability

The original string is never changed by the call.

Obsolete Markup

The name attribute is invalid on <a> today.

Modern Replacement

Use createElement() and id-based fragments.

In short: Learn anchor() so you can read and migrate legacy code — but build links with the DOM in anything new.

Understanding the anchor() Method

Calling str.anchor(name) does not create a live DOM node. It concatenates an HTML string: an opening <a name="..."> tag, the original text, and a closing </a>.

  • It is an instance method on strings (auto-boxed if needed).
  • It returns a new string — the original is unchanged.
  • Double quotes inside name become &quot;.
  • Prefer DOM APIs for real elements in the page.

📝 Syntax

General form of String.prototype.anchor:

JavaScript
str.anchor(name)

Parameters

  • name — a string (or value coerced to string) used as the name attribute in the generated <a> start tag.

Return value

A string beginning with <a name="..."> (quotes in name escaped as &quot;), then the text of str, then </a>.

Common patterns

JavaScript
"Hello, world".anchor("hello");
// 'Hello, world'

"Title".anchor('section"1');
// 'Title'

// Prefer this in new code:
const elem = document.createElement("a");
elem.id = "hello";
elem.textContent = "Hello, world";

⚡ Quick Reference

GoalCode
Legacy HTML stringstr.anchor("id")
Escape quotes in nameAutomatic ("&quot;)
Modern elementdocument.createElement("a")
Modern link targetelem.id = "hello" + href="#hello"
Use in new apps?No — deprecated

🔍 At a Glance

Four facts to remember about String.anchor().

Returns
string

HTML markup text

Status
deprecated

Compatibility only

Tag
<a name>

Obsolete attribute

Replace with
createElement

Real DOM nodes

📋 anchor() vs createElement()

str.anchor(name)document.createElement("a")
ResultHTML stringLive <a> element
Valid HTML today?No (name on <a>)Yes (use id / href)
Recommended?NoYes
Best forReading legacy codeNew UI / apps

Examples Gallery

Examples follow MDN String.anchor() patterns. Use View Output or Try It Yourself for each case.

📚 Getting Started

See the exact HTML string anchor() builds.

Example 1 — Basic anchor()

MDN-style call that wraps text with a name attribute.

JavaScript
const contentString = "Hello, world";
contentString.anchor("hello");
// 'Hello, world'
Try It Yourself

How It Works

The method returns markup text only. Nothing is added to the document until you assign it somewhere (for example innerHTML).

Example 2 — Quotes in the name

Double quotes inside name are escaped for safer HTML attributes.

JavaScript
"Title".anchor('section"1');
// 'Title'
Try It Yourself

How It Works

Escaping keeps the attribute delimiter intact when the returned string is parsed as HTML. It does not make the name attribute valid in modern HTML.

📈 Practical Patterns

Coercion, injecting markup, and the modern replacement.

Example 3 — name Is Coerced to a String

Non-string names are converted the usual way.

JavaScript
"A".anchor(123);     // 'A'
"A".anchor(true);    // 'A'
"".anchor("empty");  // ''
Try It Yourself

How It Works

Numbers and booleans become their string forms. An empty receiver still produces opening and closing tags.

Example 4 — Injecting with innerHTML (Legacy)

How older demos used the returned string — still produces obsolete markup.

JavaScript
const contentString = "Hello, world";
const html = contentString.anchor("hello");
// document.body.innerHTML = html;  // legacy pattern — avoid in new apps

console.log(html);
// Warning:  is invalid in modern HTML

How It Works

Even if the browser parses the string, the attribute is obsolete. Prefer id-based fragments for in-page links.

Example 5 — Modern Replacement with createElement()

MDN’s recommended approach — build a real element instead of HTML text.

JavaScript
const contentString = "Hello, world";
const elem = document.createElement("a");
elem.id = "hello";
elem.textContent = contentString;
elem.href = "#hello";

// document.body.appendChild(elem);
console.log(elem.outerHTML);
// 'Hello, world'
Try It Yourself

How It Works

You get a live node, valid attributes, and no string-built HTML injection. Use id (not name) as the fragment target.

Common Use Cases

Where you’ll actually meet anchor() today — mostly when reading and modernizing older code.

1. Reading Legacy Tutorials

Recognize HTML wrapper methods when they appear in old samples and books.

Example: Spotting anchor(), bold(), or fontcolor() in decade-old scripts.

2. Migrating Old Scripts

Replace deprecated wrapper calls with real DOM creation while refactoring.

Example: Swapping str.anchor(id) for document.createElement("a").

3. Teaching Immutability

Demonstrate that string methods return new values instead of mutating.

Example: Showing the original text is unchanged after calling anchor().

4. In-Page Links Today

Build jump links the modern way with an id and a fragment.

Example: id="section" on a heading + href="#section".

5. Safer Markup

Prefer DOM APIs over building HTML strings for innerHTML.

Example: Using textContent and appendChild to avoid injection.

6. Not for New Apps

Never reach for wrapper methods to build navigation in fresh projects.

Example: Choosing DOM/framework components instead of string HTML.

Pro Tip: Treat anchor() as read-only knowledge — understand it, then reach for the DOM every time you build something new.

🧠 How anchor() Builds Markup

1

Start with text + name

You call str.anchor(name) on a string receiver.

Input
2

Escape quotes in name

Double quotes become &quot; in the attribute.

Escape
3

Concatenate HTML text

Build <a name="..."> + text + </a>.

Result
4

Prefer DOM instead

Create a real <a> with id / href for valid pages.

📝 Notes

  • anchor() is deprecated — standardized only for compatibility.
  • The generated name attribute on <a> is not valid in modern HTML.
  • It returns a string, not a DOM node.
  • Other HTML wrappers (big(), blink(), bold(), fixed(), …) share the same fate.
  • Use id + fragment links for in-page navigation.
  • Avoid assigning untrusted strings to innerHTML.

Browser & Runtime Support

String.prototype.anchor() is still widely implemented for compatibility, but it is deprecated. Do not use it in new projects.

Deprecated · Legacy

String.anchor()

Available in modern browsers for old code, but MDN recommends document.createElement() instead.

Legacy Compatibility only
Google Chrome Supported · Desktop & Mobile
Full support
Mozilla Firefox Supported · Desktop & Mobile
Full support
Apple Safari Supported · macOS & iOS
Full support
Microsoft Edge Supported · Chromium
Full support
Internet Explorer No native support · Use a polyfill
Polyfill
Opera Supported · Modern versions
Full support
Samsung Internet Supported · Android
Full support
Bun Supported · JavaScript runtime
Supported
Deno Supported · JavaScript runtime
Supported
Node.js Supported · Server runtime
Supported
Android WebView Supported · Modern WebView
Full support
anchor() Avoid in new code

Bottom line: Recognize anchor() in legacy samples. For new UI, create elements with the DOM and use id-based fragments — never rely on name attributes from HTML wrapper methods.

Wrap Up

🎉 Conclusion

String.prototype.anchor() builds an obsolete <a name="..."> HTML string. It’s handy for understanding history and migrating old code — not for writing new features.

Continue with big(), at(), the String methods hub, the String constructor, or length.

In new code, create real elements with document.createElement() and use id + #fragment links.

💡 Best Practices

✅ Do

  • Use document.createElement("a") for real links
  • Set id on targets and link with href="#id"
  • Prefer textContent over string-built HTML
  • Replace anchor() when you touch legacy files
  • Learn wrappers only to recognize deprecated APIs

❌ Don’t

  • Use anchor() in new production code
  • Assume name on <a> is valid HTML
  • Inject untrusted anchor() output via innerHTML
  • Expect anchor() to return a live element
  • Mix HTML wrappers with modern component frameworks

Key Takeaways

Knowledge Unlocked

Five things to remember about String.anchor()

Deprecated HTML wrapper — prefer createElement.

5
Core concepts
⚠️ 02

Status

deprecated

Legacy
03

Markup

invalid

HTML
04

Replace

createElement

Modern
05

Mutates

no

Immutable

❓ Frequently Asked Questions

String.prototype.anchor(name) returns an HTML string that wraps the text in an <a> tag with a name attribute — for example "Hello".anchor("hi") returns '<a name="hi">Hello</a>'.
Yes. MDN marks all HTML wrapper methods as deprecated. They exist only for compatibility. Prefer document.createElement() (or modern id-based links) instead of building HTML with string methods.
The HTML specification no longer allows the name attribute on <a> elements. Named anchors are obsolete; use id on any element and link with #id instead.
No. Strings are immutable. anchor() returns a new string containing HTML markup. The original text stays the same.
Double quotes in name are escaped as &quot; so the generated attribute stays well-formed as HTML text.
It remains widely available for compatibility, but you should not use it in new code. Prefer DOM APIs.

Did you Know? 🔉

Wrapper methods like anchor(), bold(), and fontcolor() are older than the DOM APIs you use every day! They only survive so decades-old scripts don’t break — not because they’re a good way to build pages. Basically living fossils. 🦕

More String Methods

Return to the hub for slice, trim, replace, and more.

String methods hub →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful