Strings in JavaScript

SEARCH THIS SITE

Custom Search



The use of strings in Javascript is explained through examples of sample programs that you can run in order to better understand the statements used. You may also make changes to these sample program and see the outcome.

Strings in Javascript

Strings are used to store text. They are written as text between double quotes as shown in the sample program below: var x = "I am a string";. When you run the sample program below, the text in the string x is displayed.

<!DOCTYPE html>
<html>
<body>
<script>
var x = "I am a string";
alert(x);
</script>
</body>
</html>

Concatenation of Strings

In the sample program below uses the method x.concat(y,z) to concatenate (join) 3 strings to make one single string and display it. Run it and check that the displayed output is: I am a concatenated string.

<!DOCTYPE html>
<html>
<body>
<script>
var x = "I am";
var y = " a concatenated";
var z = " string";
var w = x.concat(y,z)
alert(w);
</script>
</body>
</html>

Replace a String

In the sample program below, the method x.replace("am","am not") is used to replace am by am not in the string x containing I am a concatenated string. Run the program and check that output is: I am not a concatenated string.

<!DOCTYPE html>
<html>
<body>
<script>
var x = "I am a concatenated string";
var w = x.replace("am","am not")
alert(w);
</script>
</body>
</html>

Convert a String to Upper or Lower Case

In the sample program below, the method x.toUpperCase() is used to convert the characters in the string I am being converted to upper case in the string x to upper case. Run the program and that output is: I AM BEING CONVERTED TO UPPER CASE.
In a similar way the method x.toLowerCase() may be used to convert all characters in a string to lower case.

<!DOCTYPE html>
<html>
<body>
<script>
var x = "I am being converted to upper case";
var w = x.toUpperCase();
alert(w);
</script>
</body>
</html>


Books and References

1 - A Smarter Way to Learn JavaScript: The new approach that uses technology to cut your effort in half - Mark Myers
2 - JavaScript and JQuery: Interactive Front-End Web Development 1st Edition - Jon Duckett - ISBN-13: 978-1118531648
3 - A Smarter Way to Learn HTML & CSS: Learn it faster. Remember it longer. (Volume 2) - Mark Myers
4 - http://www.w3schools.com/js/default.asp - JavaScript Tutorial