📲 Download Our Apps

EMI Calculator

Download EMI Calculator

SOA Games

Download SOA Games

SOA Technology App

Download SOA Technology

BMI Checker

Download BMI Checker

Task Jira

Download Task Jira

Laughing Adda

Download Laughing Adda

📅 हिंदी कैलेंडर ऐप डाउनलोड करें

Download Shubhcalendar App

add underscore between words javascript

To add underscores between words in a JavaScript string, effectively replacing spaces with underscores, you can use the replace() or replaceAll() methods, or a combination of split() and join().

1. Using replace() with a Regular Expression:

This method uses a regular expression to find all occurrences of spaces and replaces them with an underscore. The /g flag ensures a global replacement (all occurrences, not just the first).

JavaScript

let str = "This is a sample string";
let result = str.replace(/ /g, "_");
console.log(result); // Output: This_is_a_sample_string

2. Using replaceAll():

The replaceAll() method directly replaces all occurrences of a specified substring with another.

JavaScript

let str = "Another example string";
let result = str.replaceAll(" ", "_");
console.log(result); // Output: Another_example_string

3. Using split() and join():

This method first splits the string into an array of words using space as a delimiter, and then joins the array elements back into a string using an underscore as the separator.

JavaScript

let str = "Words separated by spaces";
let result = str.split(" ").join("_");
console.log(result); // Output: Words_separated_by_spaces



Leave a Reply

AI Spiritual Tools & Interactive Experiences

Explore powerful AI-driven tools for daily guidance, spirituality, fun quizzes, and self-discovery.

Today’s Quote

Get inspiring daily quotes powered by AI to motivate and guide your day.

Explore Now

AI Tarot Card Reader

Reveal insights about your future, love, and career with AI tarot readings.

Read Tarot

Love Match Calculator

Check compatibility and love predictions using AI-based analysis.

Check Match

Fortune Cookie

Open an AI fortune cookie and receive wisdom, luck, and fun messages.

Open Cookie

Quiz Categories

Engage with knowledge-based and fun quizzes across multiple categories.

Start Quiz

Panchang Calendar

View daily Panchang, auspicious timings, tithi, nakshatra, and festivals.

View Panchang

Online Numerology

Discover your destiny number, life path, and numerology predictions.

Calculate Now

Spiritual Feeds

Stay connected with spiritual thoughts, mantras, and divine content.

View Feeds

Quiz Hub

Attempt trending quizzes on GK, spirituality, festivals, and more.

Explore Quizzes