JavaScript String

You are Here:

JavaScript String

Strings are another basic data type available in JavaScript.

They consist of zero or more characters delimited by quotes, either single quotes or double quotes. However, the string must end with the same quote mark it started with. For example, 'Hello' (valid), "Hello" (valid), "Hello' (invalid).

Note: There is no rule for which type of quote to use.

In the following example, we will display the string "Hello" using document.write() method.

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <script> var str = "Hello"; document.write(str); </script> </body> </html>

Concatenate Two Strings

Use "+" operator to concatenate two strings.

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <script> var str1 ="Hello"; var str2 ="World"; document.write(str1 +" "+ str2); </script> </body> </html>

Quote a String

To Quote a string in the middle. Do any one of the following

  • Use Escapse Sequence (\') to quote a string.
  • Enclose a string with double quotes to single quote a string in the middle.
  • Enclose a string with single quotes to double quote a string in the middle.

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <script> var str ='she\'s is pretty'; document.write(str); // or simply var str = "she's is pretty"; document.write("<br>" +str); </script> </body> </html>

Create a String using Object

Use new String() function to create an object string.

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <script> var str1 ="One"; var str2 =new String("Two"); document.write("str1 : " +typeof str1); document.write("<br>str2 : " +typeof str2); </script> </body> </html>

Reminder

Hi Developers, we almost covered 97% of JavaScript Tutorials with examples for quick and easy learning.

We are working to cover every Single Concept in JavaScript.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author