Best Website-BuildersBest Website-Builders
    What's Hot

    A Father Who Lost His Son Was Harassed Online by Anti-Vaxxers

    April 1, 2023

    Unlimited fines for water companies dumping sewage

    April 1, 2023

    Page load speed optimization: how to speed up your site

    April 1, 2023
    Facebook Twitter Instagram
    Facebook Twitter Instagram
    Best Website-BuildersBest Website-Builders
    • Home
    • CSS

      Page load speed optimization: how to speed up your site

      April 1, 2023

      Rocket Cake 5.0 | Neowin

      March 31, 2023

      CSS Bucks County Office Helps Ukrainian Refugees – Catholic Philadelphia

      March 31, 2023

      House of Representatives Calls for Effective Implementation of CSS

      March 31, 2023

      CSS reorganized from 6 schools to 3 schools

      March 31, 2023
    • Joomla

      Evolving AlienFox Malware Steals Cloud Service Credentials

      March 31, 2023

      The Vulkan papers. 3CXDesktopApp incident. XSS flaw can lead to remote code execution. AlienFox targets misconfigured servers.

      March 31, 2023

      The Pros, Cons, and Cons of Cybersecurity – Week 13

      March 31, 2023

      34SP.com Professional Hosting Review: A Solid, Well-Supported Hosting Plan

      March 31, 2023

      10 things to consider before choosing a CMS as a freelancer

      March 30, 2023
    • PHP

      Activists cancel Vengeance Trans Day protests after threats of violence

      March 31, 2023

      Andrew Tate wins house arrest appeal in Romania

      March 31, 2023

      Should I Use ChatGPT for Therapy? What the Experts Say.

      March 31, 2023

      Biden Celebrates Trans Visibility Day, Calls Out Hateful ‘MAGA Extremists’

      March 31, 2023

      Ivanka Trump broke her silence after her father’s indictment

      March 31, 2023
    • UX

      Unizen and DWF Labs Strategic Partnership Revolutionizes Web 3.0 User Experience

      March 31, 2023

      Flamingo Transworld revamps website to take user experience to new heights

      March 31, 2023

      Kia EV9 reimagines the SUV user experience with superior design and technology

      March 31, 2023

      User Experience Is Important For Bitcoin Adoption

      March 31, 2023

      I just saw Hisense’s 85-inch UX Mini LED TV and was blown away.

      March 31, 2023
    • Web Builders
      1. Web Design
      2. View All

      What Comes First in Website Development — Design or Copy?

      February 2, 2023

      Modern Campus Honors Best Higher Education Websites of 2022

      February 2, 2023

      Premier SEO Consultant in Las Vegas, Nevada with Unparalleled Customer Service

      February 2, 2023

      Can Religious Freedom Be Saved? This group is racing the clock to teach America’s first freedom

      February 2, 2023

      How i Create New Google Account

      February 7, 2023

      CWT powers tools for meeting and event planners

      January 31, 2023

      Best Website Builder – Website Builders

      January 24, 2023

      Is There A Market For Rap-Themed Slot Games? – Rap Review

      January 19, 2023
    • WordPress

      Hisense’s ultra-bright 85-inch QLED TV is ready to compete with OLED TVs

      March 31, 2023

      This dangerous new malware seeks to target cloud systems

      March 31, 2023

      Google Photos gets major new Chromebook features

      March 31, 2023

      The Asus ROG Flow Z13 ACRNM Gaming Slate is a near-perfect rugged tablet with Windows 11 Pro and a stylus.

      March 31, 2023

      XGIMI’s Inexpensive Auto-Calibrating Projector Now Available for Mobile Movie Nights

      March 31, 2023
    • Realtoz
      • Our Other Sites
    • More News
    Best Website-BuildersBest Website-Builders
    Home » How to Convert String Case in JavaScript — SitePoint
    JavaScript

    How to Convert String Case in JavaScript — SitePoint

    websitebuildersnowBy websitebuildersnowSeptember 15, 2022No Comments4 Mins Read
    Facebook Twitter LinkedIn Telegram Pinterest Tumblr Reddit WhatsApp Email
    Share
    Facebook Twitter LinkedIn Pinterest Email


    In this tutorial, you’ll learn how to convert the case of a string to uppercase, lowercase, and title case using native JavaScript methods.

    JavaScript provides many functions and methods that allow you to manipulate data for various purposes. I recently looked at methods to convert strings to numbers, numbers to strings or ordinals, and methods to split strings. In this article, I’ll show you how to convert the case of a string. This is useful for representing strings in a particular format and for reliable string comparisons.

    convert string to lowercase

    If you want lowercase strings, use toLowerCase() Methods available on strings. This method returns a string with all letters in lowercase.

    for example:

    const str = 'HeLlO';
    console.log(str.toLowerCase()); 
    console.log(str); 
    

    by using toLowerCase() method above str Using a variable you can get the same string with all letters lowercase. Note that the new string is returned without affecting the value of . str.

    convert string to uppercase

    If you need the string to be uppercase, use toUpperCase() Methods available on strings. This method returns a string with all letters uppercase.

    for example:

    const str = 'HeLlO';
    console.log(str.toUpperCase()); 
    console.log(str); 
    

    by using toUpperCase() method above str With variables you can get the same string with all letters uppercase. Note that the new string is returned without affecting the value of . str.

    Convert string to title case

    The most common use case for converting the case of strings is converting the case of titles. This can be used to display names and headings.

    There are various ways to do this. One way is to use the method toUpperCase() At the first character of the string, concatenate it to the rest of the string. for example:

    const str = 'hello';
    console.log(str[0].toUpperCase() + str.substring(1).toLowerCase()); 
    

    In this example we get the first character using: 0 index above str variable. Then convert to uppercase using toUpperCase() Method. Finally, get the rest of the string using: substr() method to concatenate the rest of the string to the first character.you apply toLowerCase() Ensure that the remainder of the string is lowercase.

    This only converts the first letter of the word to upper case. However, in some cases, if you have a sentence, you may want to convert all words in the sentence to upper case. In that case it’s better to use a function like this:

    function toTitleCase (str) {
      if (!str) {
        return '';
      }
      const strArr = str.split(' ').map((word) => {
        return word[0].toUpperCase() + word.substring(1).toLowerCase();
      });
      return strArr.join(' ');
    }
    
    const str = 'hello world';
    console.log(toTitleCase(str)); 
    

    of toTitleCase() The function accepts one parameter. This is the string to convert to title case.

    This function first checks if the string is empty and returns an empty string if so.

    Then splitting the string on the space delimiter returns an array. Then use the map method on the array to apply the transformation we saw in the previous example to each item in the array. This will convert all words to titlecase.

    Finally, it joins the items in the array with the same space delimiter into a string and returns it.

    real example

    The following CodePen demos allow you to try out the following features: toLowerCase() and toUpperCase()If you type a string in the input, it will be displayed converted to both uppercase and lowercase. You can try using different case characters in the string.

    look at the pen
    Convert String Case in JavaScript by SitePoint (@SitePoint)
    with a code pen.

    Changing the case of string comparisons

    Strings often need to be compared before executing a block of code. If you cannot control the case of the characters in which strings are written, performing string comparisons without enforcing case can produce unexpected results.

    for example:

    const input = document.querySelector('input[type=text]');
    if (input.value === 'yes') {
      alert('Thank you for agreeing!');
    } else {
      alert('We still like you anyway')
    }
    

    If the user enters an input Yes Excluding that yesthe equality condition fails and displays the wrong alert.

    This can be resolved by forcing the string to be case sensitive.

    const input = document.querySelector('input[type=text]');
    if (input.value.toLowerCase() === 'yes') {
      alert('Thank you for agreeing!');
    } else {
      alert('We still like you anyway')
    }
    

    Conclusion

    I need to learn how to convert the case of strings in JavaScript. I often need to use it for many use cases, such as displaying a string in a particular format. It can also be used to reliably compare strings.

    Applying case to the strings you are comparing allows you to check if the contents of the strings are equal regardless of how the strings are written.

    If you found this article useful, you may also enjoy:



    Source link

    Share this:

    • Tweet
    • Email
    • Pocket
    • Mastodon
    • WhatsApp
    • Telegram
    • Share on Tumblr
    • Print
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Telegram Email
    Previous ArticleCombined approach to improve online discoverability and user experience
    Next Article CSS Corp Strengthens Operations in Costa Rica with Over 300 Staff
    websitebuildersnow
    • Website

    Related Posts

    Friend or Foe: Can Computer Coders Trust ChatGPT?

    March 31, 2023

    These are the three most in-demand tech skills this year.

    March 30, 2023

    Virtru Announces First Ever FIPS 140-2 Validated JavaScript

    March 30, 2023
    Add A Comment

    Leave a Reply Cancel reply

    Top Posts

    Subscribe to Updates

    Get the latest sports news from SportsSite about soccer, football and tennis.

    Advertisement
    Demo

    This website provides information about CSS and other things. Keep Supporting Us With the Latest News and we Will Provide the Best Of Our To Makes You Updated All Around The World News. Keep Sporting US.

    Facebook Twitter Instagram Pinterest YouTube
    Top Insights

    A Father Who Lost His Son Was Harassed Online by Anti-Vaxxers

    April 1, 2023

    Unlimited fines for water companies dumping sewage

    April 1, 2023

    Page load speed optimization: how to speed up your site

    April 1, 2023
    Get Informed

    Subscribe to Updates

    Get the latest creative news from FooBar about art, design and business.

    © 2023 bestwebsite-builders. Designed by bestwebsite-builders.
    • Home
    • About us
    • Contact us
    • DMCA
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.