JavaScript Strings - How To Work with Strings in JavaScript



JavaScript Strings

  • A JavaScript string is a sequence of characters enclosed within single quotes ('') or double quotes (""). It is a data type used to represent and manipulate text in JavaScript.

JavaScript Strings Example 1

  • A JavaScript string is zero or more characters written inside quotes.

Sample Code

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Strings</h2>

<p id="demo"></p>

<script>
let text = "kaashiv infotech";  // String written inside quotes
document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Output

JavaScript Strings
kaashiv infotech

JavaScript Strings Example 2

  • You can use single or double quotes.

Sample Code

<!DOCTYPE html>
<html>
<body>	

<h1>JavaScript Strings</h1>
<p>Strings are written inside quotes. You can use single or double quotes:</p>

<p id="demo"></p>

<script>
let Name1 = "venkat"; // Double quotes
let Name2 = 'praveen'; // Single quotes

document.getElementById("demo").innerHTML =
Name1 + " " +Name2; 
</script>
</body>
</html>

Output

JavaScript Strings
Strings are written inside quotes. You can use single or double quotes:
venkat praveen

String Length

  • To find the length of a string, use the built-in length property.

Sample Code

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<h2>The length Property</h2>
<p>The length of the string is:</p>
<p id="demo"></p>
<script>
let text = "qwertyuiopasdfghjklzxcvbnm";
document.getElementById("demo").innerHTML = text.length;
</script>
</body>
</html>

Output

JavaScript Strings
The length Property
The length of the string is:
26

Escape Character

  • Strings must be written within quotes, JavaScript will misunderstand this string.

Sample Code

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Strings</h2>
<p>The escape sequence " " inserts a double quote in a string.</p>
<p id="demo"></p>
<script>
let text = "We are the so-called \"Vikings\" from the north.";
document.getElementById("demo").innerHTML = text; 
</script>
</body>
</html>

Output

JavaScript Strings
The escape sequence " " inserts a double quote in a string.
We are the so-called "Vikings" from the north.

Related Searches to JavaScript Strings - How To Work with Strings in JavaScript