JS Reference
Html events, html objects, other references, javascript string touppercase().
Convert to uppercase:

Definition and Usage
The toUpperCase() method converts a string to uppercase letters.
The toUpperCase() method does not change the original string.
The toLowerCase() Method
The toLocaleLowerCase() Method
The toLocaleUpperCase() Method
Return Value
Related pages.
JavaScript Strings
JavaScript String Methods
JavaScript String Search
Browser Support
toUpperCase() is an ECMAScript1 (ES1) feature.
ES1 (JavaScript 1997) is fully supported in all browsers:

COLOR PICKER

Get your certification today!

Get certified by completing a course today!

Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your Suggestion:
Thank you for helping us.
Your message has been sent to W3Schools.
Top Tutorials
Top references, top examples, web certificates, get certified.
- Stack Overflow Public questions & answers
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Talent Build your employer brand
- Advertising Reach developers & technologists worldwide
- About the company
Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
How to change font inside a javascript code
I am a newbie in programming. I have here my javascript code. Its working fine but I want a different style.
this code is a random quote generator.
For example, the above code will generate random quotes. Now how do i change the font family as a result of clicking the button from this code?
Thanks in advance.
- 2 Have you tried anything? – Nick stands with Ukraine Oct 14, 2017 at 22:05
- It would be better to define classes in css, then add/remove classes from the element in JavaScript. – Joe Frambach Oct 14, 2017 at 22:10
- You can add an element and just do element.style.font = "bold 25px GreatVibes" – TheCrzyMan Nov 11, 2017 at 1:54
4 Answers 4
Looking at this:
You have no function set to onclick. Do something like:
changeFont:

Some things to improve:
- Don't use document.write , but instead reserve an element in your HTML that you will populate with the quote, assigning to textContent ;
- Don't use round in your random generating expression, but floor , otherwise you risk to produce a value that is out of range
- Don't use a separate variable for the number of quotes you have (which currently does not match the actual number), but use theQuote.length
- Don't define long style values in your HTML, but use CSS classes instead
- Don't reload the page at every click, but change the quote within the current page without navigating.
To dynamically set the font, you could reserve a few CSS classes to choose from, even randomly.
Here is how it could work:
function displayQuote() { var theQuote= [ "Whenever you see a successful business, someone once made a courageous decision. - Peter Drucker", "If you're not part of the solution, you're part of the problem. - African Proverb", "When you confront a problem you begin to solve it. - Rudy Giuliani", "I dream of painting and then I paint my dream. - Vincent Van Gogh", "Be silent or let thy words be worth more than silence. - Pythagoras", "The past cannot be changed. The future is yet in your power. - Mary Pickford", "Anything's possible if you've got enough nerve. - J.K. Rowling" ]; var quoteNum = Math.floor(Math.random() * theQuote.length); var clsName = "special" + Math.floor(Math.random() * 3); // choose random font style quote.textContent = theQuote[quoteNum]; quote.className = clsName; } next.onclick = displayQuote; // execute on click displayQuote(); // execute on page load .shareButton { background-color:blue; width:200; height:70 } .inspireButton { background-color:lightgreen; width:230; height:70; border: none; font: bold 25px GreatVibes; } .special0 { font-family: Georgia; font-size: 24px; color: #444; } .special1 { font-family: Calibri; font-size: 32px; color: #844; } .special2 { font-family: Tahoma; font-size: 28px; color: #484; } <div id="quote"> </div> <div> <button id="next" class="inspireButton">Inspire Me More!</button> </div>

As you are new, it's best not to pick up bad habits which, unfortunately is easy to do because so much of the code out there is just copied and pasted by folks who don't know any better, so:
Try not to write inline styles or inline event handlers like this:
As you can see, it makes the code difficult to read as there are 3 languages in that one element!
Instead, separate your languages into their own sections, or even files.
With regard to CSS styles, it would be better to define CSS classes ahead of time and then just switch to the class you need, rather than write all that inline CSS.
You also have some errors in your code.
So, here's an updated version of your code that also changes the font. Make sure to review the comments for details.
<html> <head> <title>Daily Quotes</title> <style> /* We'll separate the CSS into this section and prepare pre-made classes for styles. See how much cleaner this is, not only here but in the HTML as well? */ button { background-color:lightgreen; width:230;height:70; border: none; font: bold 25px GreatVibes; } .share { background-color:blue; width:200px; /* Don't forget to add the unit */ height:70px; /* Don't forget to add the unit */ } #output { /* Now, just the output area has its own style! */ font-family: fantasy; } </style> </head> <body> <!-- All your content must be between the opening and closing body tags. --> <h1>Inspirational Quotes</h1> <div> <button>Inspire Me More!</button> </div> <div> <button class="share">Share</button> <img src="images/bg.jpg" id="bg" alt="change letter javascript"> </div> <!-- Don't use document.write() to inject content into a page. Instead, prepare an element ahead of time that you will update later. --> <div id="output"></div> <!-- Place your script tags just before the closing of the body tag. That way, you can be sure that any HTML element you reference in the script has already been read into memory. --> <script> // First, get references to the HTML elements you'll want to work with: var btn = document.querySelector("button"); var out = document.getElementById("output"); // Then, set up your event handlers in JavaScript, not in HTML btn.addEventListener("click", getQuote); function getQuote(){ // Here's a simpler way to set up an array: var theQuotes= [ 'Whenever you see a successful business, someone once made a courageous decision. - Peter Drucker', 'If you\'re not part of the solution, you\'re part of the problem. - African Proverb', 'When you confront a problem you begin to solve it. - Rudy Giuliani', 'Dream of painting and then I paint my dream. - Vincent Van Gogh', 'Be silent or let thy words be worth more than silence. - Pythagoras', 'The past cannot be changed. The future is yet in your power. - Mary Pickford', 'Anything\'s possible if you\'ve got enough nerve. - J.K. Rowling' ]; // You only want your radom number to be from 0 to the amount of the quotes array -1 var quoteNum = Math.floor(Math.random() * theQuotes.length); // Now, just update the prexisting element: output.textContent = theQuotes[quoteNum]; } </script> </body> </html>

in short, here is working example: <body onload="generateRandomQuote()"> <h1>Inspirational Quotes</h1> <div id="quote-holder" style="font-family: sans-serif; color: red;"> </div> <div> <button style="background-color: lightgreen; width:230px; height:70px; border: none; font: bold 25px GreatVibes;" onclick="generateRandomQuote()">Inspire Me More!</button> </div> <button style="background-color: blue; width: 200px; height: 70px" onclick="">Share</button> <img src="images/bg.jpg" id="bg" alt="change letter javascript"> <script> var quoteHolder = document.getElementById('quote-holder'); var theQuote = [ 'Whenever you see a successful business, someone once made a courageous decision. - Peter Drucker', 'If you\'re not part of the solution, you\'re part of the problem. - African Proverb', 'When you confront a problem you begin to solve it. - Rudy Giuliani', 'I dream of painting and then I paint my dream. - Vincent Van Gogh', 'Be silent or let thy words be worth more than silence. - Pythagoras', 'The past cannot be changed. The future is yet in your power. - Mary Pickford', 'Anything\'s possible if you\'ve got enough nerve. - J.K. Rowling' ]; function generateRandomQuote() { var quoteIndex = Math.floor((Math.random() * theQuote.length)); quoteHolder.innerHTML = theQuote[ quoteIndex ]; } </script> </body>
- in css you should define units, you had just numbers,
- there shouldn't bee any h1 or images or any elements outside your body tag,
- it's better to just append your desired content to some div, rather than refreshing the whole page,
I see that you already have answer.

Your Answer
Sign up or log in, post as a guest.
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service , privacy policy and cookie policy
Not the answer you're looking for? Browse other questions tagged javascript or ask your own question .
- The Overflow Blog
- Five Stack Exchange sites turned ten years old this quarter!
- “Move fast and break things” doesn’t apply to other people’s savings (Ep. 544)
- Featured on Meta
- We've added a "Necessary cookies only" option to the cookie consent popup
- Launching the CI/CD and R Collectives and community editing features for...
- The [amazon] tag is being burninated
- Temporary policy: ChatGPT is banned
- Staging Ground Beta 1 Recap, and Reviewers needed for Beta 2
Hot Network Questions
- Separating layers based on labels
- Why did Windows 3.0 fail in Japan?
- Can I bring spices, nuts, or dates to New Zealand if they're not labeled commercially?
- Heating resistor - low current, high temperature
- Are you saving 'against' an effect if that effect applies when you successfully save?
- Forced to pay a customs fee for importing a used wedding dress into the Netherlands. Is there a way to avoid paying?
- One-day-ahead prediction of S&P500 with Temporal Convolutional Networks
- Ash - Complex Variables - Proof of Maximum Principle
- How does an ideal prior distribution needs a probability mass on zero to reduce variance, and have fat tails to reduce bias?
- What is the name of the color used by the SBB (Swiss Federal Railway) in the 1920s to paint their locomotive?
- Would Fey Ancestry affect Cutting Words?
- Checksum of secret data
- Gunslinger Fake Out with Covered Reload
- How to transport a knife that falls under the Weapons Act
- How does one perform amplitude encoding using only unitary gates?
- What laws would Jesus be breaking if he were to turn water into wine today?
- Does the attacker need to be on the same network to carry out a deauthentication attack?
- Multiple stays in EU not longer than 90 days each time?
- An Effective Splash Cymbal
- Probability of positive inner product with expectation of one variable
- Should I put my dog down to help the homeless?
- How do/should administrators estimate the cost of producing an online introductory mathematics class?
- Concrete base for parcel box
- Animation which involves a spherical floating robot and a little girl
Your privacy
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .
// Tutorial //
How to index, split, and manipulate strings in javascript.
- Development

By Tania Rascia
Introduction
A string is a sequence of one or more characters that may consist of letters, numbers, or symbols. Each character in a JavaScript string can be accessed by an index number, and all strings have methods and properties available to them.
In this tutorial, we will learn the difference between string primitives and the String object, how strings are indexed, how to access characters in a string, and common properties and methods used on strings.
String Primitives and String Objects
First, we will clarify the two types of strings. JavaScript differentiates between the string primitive , an immutable datatype, and the String object.
In order to test the difference between the two, we will initialize a string primitive and a string object.
We can use the typeof operator to determine the type of a value. In the first example, we simply assigned a string to a variable.
In the second example, we used new String() to create a string object and assign it to a variable.
Most of the time you will be creating string primitives. JavaScript is able to access and utilize the built-in properties and methods of the String object wrapper without actually changing the string primitive you’ve created into an object.
While this concept is a bit challenging at first, you should be aware of the distinction between primitive and object. Essentially, there are methods and properties available to all strings, and in the background JavaScript will perform a conversion to object and back to primitive every time a method or property is called.
How Strings are Indexed
Each of the characters in a string correspond to an index number, starting with 0 .
To demonstrate, we will create a string with the value How are you? .
The first character in the string is H , which corresponds to the index 0 . The last character is ? , which corresponds to 11 . The whitespace characters also have an index, at 3 and 7 .
Being able to access every character in a string gives us a number of ways to work with and manipulate strings.
Accessing Characters
We’re going to demonstrate how to access characters and indices with the How are you? string.
Using square bracket notation, we can access any character in the string.
We can also use the charAt() method to return the character using the index number as a parameter.
Alternatively, we can use indexOf() to return the index number by the first instance of a character.
Although “o” appears twice in the How are you? string, indexOf() will get the first instance.
lastIndexOf() is used to find the last instance.
For both of these methods, you can also search for multiple characters in the string. It will return the index number of the first character in the instance.
The slice() method, on the other hand, returns the characters between two index numbers. The first parameter will be the starting index number, and the second parameter will be the index number where it should end.
Note that 11 is ? , but ? is not part of the returned output. slice() will return what is between, but not including, the last parameter.
If a second parameter is not included, slice() will return everything from the parameter to the end of the string.
To summarize, charAt() and slice() will help return string values based on index numbers, and indexOf() and lastIndexOf() will do the opposite, returning index numbers based on the provided string characters.
Finding the Length of a String
Using the length property, we can return the number of characters in a string.
Remember that the length property is returning the actual number of characters starting with 1, which comes out to 12, not the final index number, which starts at 0 and ends at 11 .
Converting to Upper or Lower Case
The two built-in methods toUpperCase() and toLowerCase() are helpful ways to format text and make textual comparisons in JavaScript.
toUpperCase() will convert all characters to uppercase characters.
toLowerCase() will convert all characters to lowercase characters.
These two formatting methods take no additional parameters.
It is worth noting that these methods do not change the original string.
Splitting Strings
JavaScript has a very useful method for splitting a string by a character and creating a new array out of the sections. We will use the split() method to separate the array by a whitespace character, represented by " " .
Now that we have a new array in the splitString variable, we can access each section with an index number.
If an empty parameter is given, split() will create a comma-separated array with each character in the string.
By splitting strings you can determine how many words are in a sentence, and use the method as a way to determine people’s first names and last names, for example.
Trimming Whitespace
The JavaScript trim() method removes white space from both ends of a string, but not anywhere in between. Whitespace can be tabs or spaces.
The trim() method is a simple way to perform the common task of removing excess whitespace.
Finding and Replacing String Values
We can search a string for a value, and replace it with a new value using the replace() method. The first parameter will be the value to be found, and the second parameter will be the value to replace it with.
In addition to being able to replace a value with another string value, we can also use Regular Expressions to make replace() more powerful. For instance, replace() only affects the first value, but we can use the g (global) flag to catch all instances of a value, and the i (case insensitive) flag to ignore case.
This is a very common task that makes use of Regular Expressions. Visit Regexr to practice more examples of RegEx.
Strings are one of the most frequently used data types, and there is a lot we can do with them.
In this tutorial, we learned the difference between the string primitive and String object, how strings are indexed, and how to use the built-in methods and properties of strings to access characters, format text, and find and replace values.
For a more general overview on strings, read the tutorial “ How To Work with Strings in JavaScript .”
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Learn more about us
Tutorial Series: How To Code in JavaScript
JavaScript is a high-level, object-based, dynamic scripting language popular as a tool for making webpages interactive.
- 1/37 How To Use the JavaScript Developer Console
- 2/37 How To Add JavaScript to HTML
- 3/37 How To Write Your First JavaScript Program
Still looking for an answer?
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
I’m afraid there is a slight inaccuracy here: "If an empty parameter is given, split() will create a comma-separated array with each character in the string." This way split() creates an array with the string. And to create a comma-separated array with each character in the string we should use .split( '' ) .
Thank you very much. Your articles are very useful =)
This comment has been deleted

Popular Topics
- Linux Basics
- All tutorials
- Free Managed Hosting
Try DigitalOcean for free
Join the tech talk.
Please complete your information!
How to Capitalize the First Letter of Each Word in JavaScript – a JS Uppercase Tutorial
In this article, you are going to learn how to capitalize the first letter of any word in JavaScript. After that, you are going to capitalize the first letter of all words from a sentence.
The beautiful thing about programming is that there is no one universal solution to solve a problem. Therefore, in this article you are going to see multiple ways of solving the same problem.

Capitalize the first letter of a word
First of all, let's start with capitalizing the first letter of a single word. After you learn how to do this, we'll proceed to the next level – doing it on every word from a sentence. Here is an example:
In JavaScript, we start counting from 0. For instance, if we have an array, the first position is 0, not 1.
Also, we can access each letter from a String in the same way that we access an element from an array. For instance, the first letter from the word " freeCodeCamp " is at position 0.
This means that we can get the letter f from freeCodeCamp by doing publication[0] .
In the same way, you can access other letters from the word. You can replace "0" with any number, as long as you do not exceed the word length. By exceeding the word length, I mean trying to do something like publication[25 , which throws an error because there are only twelve letters in the word "freeCodeCamp".
How to capitalize the first letter
Now that we know how to access a letter from a word, let's capitalize it.
In JavaScript, we have a method called toUpperCase() , which we can call on strings, or words. As we can imply from the name, you call it on a string/word, and it is going to return the same thing but as an uppercase.
For instance:
Running the above code, you are going to get a capital F instead of f. To get the whole word back, we can do this:
Now it concatenates "F" with "reeCodeCamp", which means we get back the word "FreeCodeCamp". That is all!
Let's recap
To be sure things are clear, let's recap what we've learnt so far:
- In JavaScript, counting starts from 0.
- We can access a letter from a string in the same way we access an element from an array - e.g. string[index] .
- Do not use an index that exceeds the string length (use the length method - string.length - to find the range you can use).
- Use the built-in method toUpperCase() on the letter you want to transform to uppercase.
Capitalize the first letter of each word from a string
The next step is to take a sentence and capitalize every word from that sentence. Let's take the following sentence:
Split it into words
We have to capitalize the first letter from each word from the sentence freeCodeCamp is an awesome resource .
The first step we take is to split the sentence into an array of words. Why? So we can manipulate each word individually. We can do that as follows:
Iterate over each word
After we run the above code, the variable words is assigned an array with each word from the sentence. The array is as follows ["freeCodeCamp", "is", "an", "awesome", "resource"] .
Now the next step is to loop over the array of words and capitalize the first letter of each word.
In the above code, every word is taken separately. Then it capitalizes the first letter, and in the end, it concatenates the capitalized first letter with the rest of the string.
Join the words
What is the above code doing? It iterates over each word, and it replaces it with the uppercase of the first letter + the rest of the string.
If we take "freeCodeCamp" as an example, it looks like this freeCodeCamp = F + reeCodeCamp .
After it iterates over all the words, the words array is ["FreeCodeCamp", "Is", "An", "Awesome", "Resource"] . However, we have an array, not a string, which is not what we want.
The last step is to join all the words to form a sentence. So, how do we do that?
In JavaScript, we have a method called join , which we can use to return an array as a string. The method takes a separator as an argument. That is, we specify what to add between words, for example a space.
In the above code snippet, we can see the join method in action. We call it on the words array, and we specify the separator, which in our case is a space.
Therefore, ["FreeCodeCamp", "Is", "An", "Awesome", "Resource"] becomes FreeCodeCamp Is An Awesome Resource .
Other methods
In programming, usually, there are multiple ways of solving the same problem. So let's see another approach.
What is the difference between the above solution and the initial solution? The two solutions are very similar, the difference being that in the second solution we are using the map function, whereas in the first solution we used a for loop .
Let's go even further, and try to do a one-liner . Be aware! One line solutions might look cool, but in the real world they are rarely used because it is challenging to understand them. Code readability always comes first.
The above code uses RegEx to transform the letters. The RegEx might look confusing, so let me explain what happens:
- ^ matches the beginning of the string.
- \w matches any word character.
- {1} takes only the first character.
- Thus, ^\w{1} matches the first letter of the word.
- | works like the boolean OR . It matches the expression after and before the | .
- \s+ matches any amount of whitespace between the words (for example spaces, tabs, or line breaks).
Thus, with one line, we accomplished the same thing we accomplished in the above solutions. If you want to play around with the RegEx and to learn more, you can use this website .
Congratulations, you learnt a new thing today! To recap, in this article, you learnt how to:
- access the characters from a string
- capitalize the first letter of a word
- split a string in an array of words
- join back the words from an array to form a string
- use RegEx to accomplish the same task
Thanks for reading! If you want to keep in touch, let's connect on Twitter @catalinmpit . I also publish articles regularly on my blog catalins.tech if you want to read more content from me.
Developer. Content creator. Technical writer You can find me hanging around at https://catalins.tech
If you read this far, tweet to the author to show them you care. Tweet a thanks
Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Level Up Coding

Mar 11, 2020
Member-only
JavaScript Algorithm: Letter Changes
For today’s algorithm, we are going to write a function called LetterChanges that will take one string, str as input.
You are given a string and for each string given you modify it by replacing each letter to the letter that goes after it in the alphabet. You change only the alphabetical characters. After replacing all the necessary letters, you then take all the vowels from that newly created string and capitalize them. The function will return the string after all the changes.
Let’s use an example:
For our input string, we change all of our alphabetical characters (leaving the *3 alone) to the letter that comes after it in the alphabet, our string becomes:
Then we go back and find all the vowels, if any, in our new string and capitalize them. In the end, our function will return:
Now we proceed to turn this into code.
First, we create a variable called strArray . With this variable, we convert our string input into an array. We first use the toLowerCase() method to lowercase our string before we split the characters to create our array.
Next, we create another variable called letterChange . This variable holds our string after changing each letter to the letter following it in the alphabet. To iterate through the array we use the Array map() method.
The map method allows us to iterate through an array and use our callback function on every element on the array.
Inside our callback function, we use a combination of String.fromCharCode() and charCodeAt() to get the Unicode value for each character and the character associated with a specific Unicode value. We only want to change the letters that are a-z (not A-Z, capitalized letters have different Unicode values). Any Unicode value that doesn’t translate to those characters we leave alone. If we look at an ASCII table, these non-alphabetical (and capitalized alphabetical letters) characters have Unicode values that are less than 97 or greater than 122.
To get the next letter in the alphabet we first have to get the Unicode value of the current character and add 1. We retrieve the index of the current character to use inside the charCodeAt() method. String.fromCharCode() will give us the character associated with that Unicode value.
Now we have our string (still in array form) of our modified characters but we are not done. The next thing is checking the string for any vowels so we can capitalize them.
We use the map method one more time to iterate and modify the letterChange array variable again but this time to include the capitalized vowels.
Inside our map method, we use a method from the regular expression object called test() . What test() does is it searches for a match between the regular expression and the input string and if the regular expression pattern exists in the string the method will output true. If not, false.
We use our regular expression pattern /[aeiou]/ to see if each character is a vowel. If it is, we simply use the toUpperCase() method to capitalize it. If the character is not a vowel or a letter at all, return the character as is.
Now that we are done, we can return our letterChange variable but first, we join it so we can return it as a string.
And that concludes our code. There are probably some parts that could use some improvements but again, this is one way to solve this. Here is the rest of the code:
If you found this algorithm helpful, check out my other recent JavaScript algorithm solutions:
JavaScript Algorithm: Alternating Characters
For today’s algorithm, we are going to write a function called alternatingcharacters that will take one string, s as…, javascript algorithm: introduction, today’s algorithm will be a simple short one but we are going to write a function called intro that will take in an….
levelup.gitconnected.com
JavaScript Algorithm: Beautiful Days at the Movies
For today’s algorithm, we are going to write a function called beautifuldays that will take in three integers as…, more from level up coding.
Coding tutorials and news. The developer homepage gitconnected.com && skilled.dev && levelup.dev
About Help Terms Privacy
Get the Medium app

An illustrator that writes humor and satire about everything and nothing at the same time. Like my stories? Leave a tip at: https://ko-fi.com/ofcuriousbirds
Text to speech
- Coding Ground
- Corporate Training
- Trending Categories

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
Change every letter to next letter - JavaScript
We are required to write a JavaScript function that takes in a string and changes every letter of the string from the English alphabets to its succeeding element.
For example: If the string is −
Then the output should be −
Following is the code −
Following is the output in the console −

0 Followers
- Related Articles
- How to Automatically Increase a Letter by One to Get the Next Letter in Excel?
- Finding the immediate next character to a letter in string using JavaScript
- Program to make vowels in string uppercase and change letters to next letter in alphabet (i.e. z->a) in JavaScript
- Repeating letter string - JavaScript
- JavaScript Count repeating letter
- How to change the Drive letter using PowerShell?
- Convert number to alphabet letter JavaScript
- Missing letter from strings in JavaScript
- Finding letter distance in strings - JavaScript
- Delete every one of the two strings that start with the same letter in JavaScript
- A Letter to God
- Swapping letter with succeeding alphabet in JavaScript
- Finding missing letter in a string - JavaScript
- Capitalizing first letter of each word JavaScript
- How to change all caps to lowercase except first letter in Excel?

How to replace character inside a string in JavaScript
Topic: JavaScript / jQuery Prev | Next
Answer: Use the JavaScript replace() method
You can use the JavaScript replace() method to replace the occurrence of any character in a string. However, the replace() will only replace the first occurrence of the specified character. To replace all the occurrence you can use the global ( g ) modifier. The following example will show you how to replace all underscore ( _ ) character in a string with hyphen ( - ).
Related FAQ
Here are some more FAQ related to this topic:
- How to remove white space from a string using jQuery
- How to find substring between the two words using jQuery
- How to get substring from a string using jQuery

Is this website helpful to you? Please give us a like , or share your feedback to help us improve . Connect with us on Facebook and Twitter for the latest updates.
Interactive Tools

JavaScript Change Text

This tutorial will discuss how to change text of an element using the textContent property and createTextNode() function in JavaScript.
Please enable JavaScript
Change Text of an Element Using the textContent Property in JavaScript
Change text of an element using the createtextnode() function in javascript.
If you want to append the new text with the old text, you need to get that element using its id or class name and then using the createTextNode() function, you can create a node of the new text and using the appendChild() function you can append the new text with the old text. If an id or class name is not specified, you can use the id or class attribute to give the element an id or class name. Ensure the id or class name is unique; otherwise, any element having the same id will also be changed. For example, let’s create a text element using the span tag and append its text using the createTextNode() function in JavaScript. See the code below.
Hello! I am Ammar Ali, a programmer here to learn from experience, people, and docs, and create interesting and useful programming content. I mostly create content about Python, Matlab, and Microcontrollers like Arduino and PIC.
Related Article - JavaScript Text
- Data Structure & Algorithm Classes (Live)
- System Design (Live)
- DevOps(Live)
- Explore More Live Courses
- Interview Preparation Course
- Data Science (Live)
- GATE CS & IT 2024
- Data Structure & Algorithm-Self Paced(C++/JAVA)
- Data Structures & Algorithms in Python
- Explore More Self-Paced Courses
- C++ Programming - Beginner to Advanced
- Java Programming - Beginner to Advanced
- C Programming - Beginner to Advanced
- Full Stack Development with React & Node JS(Live)
- Java Backend Development(Live)
- Android App Development with Kotlin(Live)
- Python Backend Development with Django(Live)
- Complete Data Science Program(Live)
- Mastering Data Analytics
- DevOps Engineering - Planning to Production
- CBSE Class 12 Computer Science
- School Guide
- All Courses
- Linked List
- Binary Tree
- Binary Search Tree
- Advanced Data Structure
- All Data Structures
- Asymptotic Analysis
- Worst, Average and Best Cases
- Asymptotic Notations
- Little o and little omega notations
- Lower and Upper Bound Theory
- Analysis of Loops
- Solving Recurrences
- Amortized Analysis
- What does 'Space Complexity' mean ?
- Pseudo-polynomial Algorithms
- Polynomial Time Approximation Scheme
- A Time Complexity Question
- Searching Algorithms
- Sorting Algorithms
- Graph Algorithms
- Pattern Searching
- Geometric Algorithms
- Mathematical
- Bitwise Algorithms
- Randomized Algorithms
- Greedy Algorithms
- Dynamic Programming
- Divide and Conquer
- Backtracking
- Branch and Bound
- All Algorithms
- Company Preparation
- Practice Company Questions
- Interview Experiences
- Experienced Interviews
- Internship Interviews
- Competitive Programming
- Design Patterns
- System Design Tutorial
- Multiple Choice Quizzes
- Go Language
- Tailwind CSS
- Foundation CSS
- Materialize CSS
- Semantic UI
- Angular PrimeNG
- Angular ngx Bootstrap
- jQuery Mobile
- jQuery EasyUI
- React Bootstrap
- React Rebass
- React Desktop
- React Suite
- ReactJS Evergreen
- ReactJS Reactstrap
- BlueprintJS
- TensorFlow.js
- English Grammar
- School Programming
- Number System
- Trigonometry
- Probability
- Mensuration
- Class 8 Syllabus
- Class 9 Syllabus
- Class 10 Syllabus
- Class 11 Syllabus
- Class 8 Notes
- Class 9 Notes
- Class 10 Notes
- Class 11 Notes
- Class 12 Notes
- Class 8 Formulas
- Class 9 Formulas
- Class 10 Formulas
- Class 11 Formulas
- Class 8 Maths Solution
- Class 9 Maths Solution
- Class 10 Maths Solution
- Class 11 Maths Solution
- Class 12 Maths Solution
- Class 7 Notes
- History Class 7
- History Class 8
- History Class 9
- Geo. Class 7
- Geo. Class 8
- Geo. Class 9
- Civics Class 7
- Civics Class 8
- Business Studies (Class 11th)
- Microeconomics (Class 11th)
- Statistics for Economics (Class 11th)
- Business Studies (Class 12th)
- Accountancy (Class 12th)
- Macroeconomics (Class 12th)
- Machine Learning
- Data Science
- Mathematics
- Operating System
- Computer Networks
- Computer Organization and Architecture
- Theory of Computation
- Compiler Design
- Digital Logic
- Software Engineering
- GATE 2024 Live Course
- GATE Computer Science Notes
- Last Minute Notes
- GATE CS Solved Papers
- GATE CS Original Papers and Official Keys
- GATE CS 2023 Syllabus
- Important Topics for GATE CS
- GATE 2023 Important Dates
- Software Design Patterns
- HTML Cheat Sheet
- CSS Cheat Sheet
- Bootstrap Cheat Sheet
- JS Cheat Sheet
- jQuery Cheat Sheet
- Angular Cheat Sheet
- Facebook SDE Sheet
- Amazon SDE Sheet
- Apple SDE Sheet
- Netflix SDE Sheet
- Google SDE Sheet
- Wipro Coding Sheet
- Infosys Coding Sheet
- TCS Coding Sheet
- Cognizant Coding Sheet
- HCL Coding Sheet
- FAANG Coding Sheet
- Love Babbar Sheet
- Mass Recruiter Sheet
- Product-Based Coding Sheet
- Company-Wise Preparation Sheet
- Array Sheet
- String Sheet
- Graph Sheet
- ISRO CS Original Papers and Official Keys
- ISRO CS Solved Papers
- ISRO CS Syllabus for Scientist/Engineer Exam
- UGC NET CS Notes Paper II
- UGC NET CS Notes Paper III
- UGC NET CS Solved Papers
- Campus Ambassador Program
- School Ambassador Program
- Geek of the Month
- Campus Geek of the Month
- Placement Course
- Testimonials
- Student Chapter
- Geek on the Top
- Geography Notes
- History Notes
- Science & Tech. Notes
- Ethics Notes
- Polity Notes
- Economics Notes
- UPSC Previous Year Papers
- SSC CGL Syllabus
- General Studies
- Subjectwise Practice Papers
- Previous Year Papers
- SBI Clerk Syllabus
- General Awareness
- Quantitative Aptitude
- Reasoning Ability
- SBI Clerk Practice Papers
- SBI PO Syllabus
- SBI PO Practice Papers
- IBPS PO 2022 Syllabus
- English Notes
- Reasoning Notes
- Mock Question Papers
- IBPS Clerk Syllabus
- Apply for a Job
- Apply through Jobathon
- Hire through Jobathon
- All DSA Problems
- Problem of the Day
- GFG SDE Sheet
- Top 50 Array Problems
- Top 50 String Problems
- Top 50 Tree Problems
- Top 50 Graph Problems
- Top 50 DP Problems
- Solving For India-Hackthon
- GFG Weekly Coding Contest
- Job-A-Thon: Hiring Challenge
- BiWizard School Contest
- All Contests and Events
- Saved Videos
- What's New ?
- JS-Function
- JS-Generator
- JS-Expressions
- JS-ArrayBuffer
- JS-Tutorial
- Web Development
- Web-Technology
Related Articles
- Write Articles
- Pick Topics to write
- Guidelines to Write
- Get Technical Writing Internship
- Write an Interview Experience
- How to convert string to camel case in JavaScript ?
How to make first letter of a string uppercase in JavaScript ?
- JavaScript String toUpperCase() Method
- JavaScript String toLowerCase() Method
- JavaScript String split() Method
- JavaScript | Split a string with multiple separators
- Split an array into chunks in JavaScript
- Check if an array is empty or not in JavaScript
- How to check if a variable is an array in JavaScript?
- Most useful JavaScript Array Functions – Part 2
- Must use JavaScript Array Functions – Part 3
- Arrays in JavaScript
- JavaScript Basic Array Methods
- JavaScript Array map() Method
- JavaScript Array findIndex() Method
- JavaScript Array entries() Method
- JavaScript Array every() Method
- JavaScript Array copyWithin() Method
- JavaScript array.values() Function
- JavaScript Array find() Method
- JavaScript Array filter() Method
- ES6 | Array filter() Method
- ES6 | Array forEach() Method
- Node.js forEach() function
- Node.js push() function
- How to calculate the number of days between two dates in JavaScript ?
- File uploading in React.js
- Hide elements in HTML using display property
- How to append HTML code to a div using JavaScript ?
- Difference between var and let in JavaScript
- Last Updated : 04 Jan, 2023
In this article, we will convert the first letter of a string to uppercase in Javascript.
There are a number of ways to capitalize the first letter of the string in JavaScript .
- Using toUpperCase() method
- Using slice() method
- Using charAt() method
- Using replace() method
JavaScript toUpperCase() Function : This function applies on a string and changes all letters to uppercase.
JavaScript slice() Function : This function applies to a string and slices it according to the passed parameter.
Example: This example uses the slice() method to convert the first letter to uppercase.
JavaScript charAt() Function : This charAt() function returns the character at a given position in the string.
Example: This example uses charAT() method to make the first letter of a string uppercase.
JavaScript replace() Function : This is a built-in function in JavaScript that is used to replace a slice of a string with another string or a regular expression. The original string will not be affected.
The below examples show the conversion to uppercase using the above-described methods.
Example: This example uses string.replace() method to make the first letter of a string uppercase.
Please Login to comment...
- amitsingh2730
- JavaScript-Questions
- javascript-string
- Web Technologies
New Course Launch!
Improve your Coding Skills with Practice
Start your coding journey now.
How to change Text in Paragraph using JavaScript?
Javascript – change text in paragraph.
To change the text in a paragraph using JavaScript, get reference to the paragraph element, and assign new text as string value to the innerHTML property of the paragraph element.
Change text in Paragraph using JavaScript
This is a paragraph.
In this JavaScript Tutorial , we learned how to change the text in a paragraph using JavaScript.
Related Tutorials
- How to Change Border Color of Paragraph in JavaScript?
- How to Change Border Radius of Paragraph in JavaScript?
- How to Change Border Style of Paragraph in JavaScript?
- How to Change Border Width of Paragraph in JavaScript?
- How to Change Bottom Border of Paragraph in JavaScript?
- How to Change Font Color of Paragraph in JavaScript?
- How to Change Font Family of Paragraph in JavaScript?
- How to Change Font Size of Paragraph in JavaScript?
- How to Change Font Weight of Paragraph in JavaScript?
- How to Change Height of Paragraph in JavaScript?
- How to Change Left Border of Paragraph in JavaScript?
- How to Change Margin of Paragraph in JavaScript?
- How to Change Opacity of Paragraph in JavaScript?
- How to Change Padding of Paragraph in JavaScript?
- How to Change Paragraph Text to Bold in JavaScript?
- How to Change Paragraph Text to Italic in JavaScript?
- How to Change Right Border of Paragraph in JavaScript?
- How to Change Top Border of Paragraph in JavaScript?
- How to Change Width of Paragraph in JavaScript?
- How to Change the Background Color of Paragraph in JavaScript?
- How to Change the Border of Paragraph in JavaScript?
- How to Clear Inline Style of Paragraph in JavaScript?
- How to Hide Paragraph in JavaScript?
- How to Underline Text in Paragraph in JavaScript?
- How to get Attributes of Paragraph Element in JavaScript?
Most Read Articles

IMAGES
VIDEO
COMMENTS
In JavaScript, strings are immutable, which means the best you can do is to create a new string with the changed content and assign the variable to point to it. You'll need to define the replaceAt () function yourself:
Definition and Usage The replace () method searches a string for a value or a regular expression. The replace () method returns a new string with the value (s) replaced. The replace () method does not change the original string. Note If you replace a value, only the first instance will be replaced.
The toUpperCase () method converts a string to uppercase letters. The toUpperCase () method does not change the original string. See Also: The toLowerCase () Method The toLocaleLowerCase () Method The toLocaleUpperCase () Method Syntax string .toUpperCase () Parameters NONE Return Value Related Pages JavaScript Strings JavaScript String Methods
In JavaScript, strings are immutable, meaning that they cannot be changed in place. Even though you can read each character of a string, you cannot write to it. You can solve the problem with a regular expression replace: output = input.replace (/a/g, '4').replace (/i/g, '1');
That way, you can be sure that any HTML element you reference in the script has already been read into memory. --> <script> // First, get references to the HTML elements you'll want to work with: var btn = document.querySelector("button"); var out = document.getElementById("output"); // Then, set up your event handlers in JavaScript, not in ...
Finding the Length of a String. Using the length property, we can return the number of characters in a string. Remember that the length property is returning the actual number of characters starting with 1, which comes out to 12, not the final index number, which starts at 0 and ends at 11.
Strings in JavaScript are immutable. The toLowerCase () method converts the string specified into a new one that consists of only lowercase letters and returns that value. It means that the old, original string is not changed or affected in any way. let myGreeting = 'Hey there!'; console.log (myGreeting.toLowerCase ()); //output //hey there!
Use the built-in method toUpperCase () on the letter you want to transform to uppercase. Capitalize the first letter of each word from a string The next step is to take a sentence and capitalize every word from that sentence. Let's take the following sentence: const mySentence = "freeCodeCamp is an awesome resource"; Split it into words
For our input string, we change all of our alphabetical characters (leaving the *3 alone) to the letter that comes after it in the alphabet, our string becomes: ifmmp*3. Then we go back and find all the vowels, if any, in our new string and capitalize them. In the end, our function will return: Ifmmp*3. Now we proceed to turn this into code.
We are required to write a JavaScript function that takes in a string and changes every letter of the string from the English alphabets to its succeeding element. For example: If the string is − const str = 'how are you'; Then the output should be − const output = 'ipx bsf zpv' Example Following is the code −
Related FAQ. Here are some more FAQ related to this topic: How to remove white space from a string using jQuery; How to find substring between the two words using jQuery
Approach: Create a label element and assign an id to that element. Define a button that is used to call a function. It acts as a switch to change the text in the label element. Define a javaScript function, that will update the label text. Use the innerHTML property to change the text inside the label.
Change Text of an Element Using the createTextNode () Function in JavaScript. If you want to append the new text with the old text, you need to get that element using its id or class name and then using the createTextNode () function, you can create a node of the new text and using the appendChild () function you can append the new text with ...
There are a number of ways to capitalize the first letter of the string in JavaScript . Using toUpperCase () method Using slice () method Using charAt () method Using replace () method JavaScript toUpperCase () Function: This function applies on a string and changes all letters to uppercase. Syntax: string.toUpperCase ()
JavaScript - Change Text in Paragraph. To change the text in a paragraph using JavaScript, get reference to the paragraph element, and assign new text as string value to the innerHTML property of the paragraph element. Example