Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to remove the first character of link (anchor text) in JavaScript?
In JavaScript, you can remove the first character from link anchor text using the substring(1) method combined with DOM manipulation. This is useful when you need to programmatically fix incorrectly formatted link text.
The Problem
Sometimes links may have extra characters at the beginning that need to be removed. For example, "Aabout_us" should be "about_us" and "Hhome_page" should be "home_page".
Using substring(1) Method
The substring(1) method extracts characters from index 1 to the end, effectively removing the first character (index 0).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Remove First Character from Links</title>
</head>
<body>
<div class="linkDemo">
<div>
<a href="#">Aabout_us</a>
</div>
</div>
<div class="linkDemo">
<div>
<a href="#">Hhome_page</a>
</div>
</div>
<script>
// Select all links and remove first character from their text
[...document.querySelectorAll('.linkDemo div a')].forEach(link => {
link.innerHTML = link.innerHTML.substring(1);
});
</script>
</body>
</html>
Alternative Method: Using textContent
For better security and when dealing with plain text, use textContent instead of innerHTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Remove First Character - Safe Method</title>
</head>
<body>
<div>
<a href="#" id="link1">Xcontact_us</a>
<a href="#" id="link2">Sservices</a>
</div>
<script>
// Using textContent for safer text manipulation
const links = document.querySelectorAll('a');
links.forEach(link => {
if (link.textContent.length > 1) {
link.textContent = link.textContent.substring(1);
}
});
</script>
</body>
</html>
How It Works
The code works by:
- Selecting all anchor elements using
querySelectorAll() - Using
forEach()to iterate through each link - Applying
substring(1)to remove the first character - Updating the link text with the modified string
Key Points
-
substring(1)starts from index 1, removing the character at index 0 - Use
textContentfor plain text to avoid XSS vulnerabilities - Use
innerHTMLonly when you need to preserve HTML formatting - Always check string length before manipulation to avoid errors
Conclusion
The substring(1) method provides a simple way to remove the first character from link text. Use textContent for safety when dealing with plain text content.
