JS: String | JavaScript
JavaScript String
var s = "this is string may contain any character within quotes";
String is a primitive data type in JavaScript, containg a stream of characters. The string characters may be given within double-quote " or double single-quote ', there is not difference in effect.
var x = "string within double-quotes";
var y = 'string within single-quotes';
JavaScript String Unicode
JavaScript String accepts Unicode in four-digit Hexadecimal format follwed by \u
var uc = "\u2718"
✘
Single or double Quotes in string
A string value may also require single or double quotes with string. This can be achieved with escapsequence '\''
.
var str = 'This is my friend\'s home';
"This is my friend's home"
Similarly, double quotes may also be added to the string:
var str = "Martin Luther King Jr. said, \"Injustice anywhere is threat to justice everywhere\"";
'Martin Luther King Jr. said, "Injustice anywhere is threat to justice everywhere"'
anything just after \ within a string is called escape sequence e.g.'\\'
for backslash and'\t'
for Tab.
string length
length
property returns the number of characters
var str = 'PiTribe.com';
console.log(str.length);
11
The length
property returns character count of the output string, not the input string. Have a look:
var str = '\u00a9 PiTribe.com';
console.log(str);
var len = str.length;
console.log(len);
© PiTribe.com
13
As the string \u00a9 PiTribe.com
contains 18
characters, if we count, before assigned to str, but returned 13
.
This is because \u00a9
is treated as one character only because this is a unicode character for copyright symbol ©.
string charCode
string charCodeAt
string concat
concat
function combines two string:
var str = 'PiTribe';
var txt = 'Tutorial';
var combined = str.concat(txt);
console.log(combined);
PiTribeTutorial
There is no change in str and txt variables because concat
returns the combined string without effecting original strings being joined.
We can add as much arguments as much required.
var str = 'PiTribe';
var txt = 'Tutorial';
var combined = str.concat(' ', txt);
console.log(combined);
PiTribe Tutorial
In the example above, we added blank space ' '
as argument before txt.
string endsWith
endsWith
checks either a string has the searchString at end of the string.
var str = 'PiTribe';
var searchString = 'be';
var endPosition = 0;
var ends = str.endsWith(searchString, endPosition);
if(ends)
console.log('Ends with string')
else
console.log('Does not end with string');
Ends with string
In the example, looking for searchString be
in str from the endPosition.
endPosition is 0-based index
string includes
string lastIndexOf
string match
string padEnd
string padStart
string replace
string split
string substr
string substring
string toLowerCase
string toUpperCase
string trim
string trimStart
string trimEnd
string trimLeft
string trimRight
- JavaScript String may contain any ASCII character
- JavaScript String support Unicode characters