JavaScript String Methods
String methods help you to work with strings.
String Methods and Properties
Primitive values, like “John Doe”, cannot have properties or methods (because they are not objects).
But with JavaScript, methods and properties are also available to primitive values, because JavaScript treats primitive values as objects when executing methods and properties.
JavaScript String Length
The length
property returns the length of a string:
Example
let txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let length = txt.length;
Extracting String Parts
There are 3 methods for extracting a part of a string:
slice(start, end)
substring(start, end)
substr(start, length)
JavaScript String slice()
slice()
extracts a part of a string and returns the extracted part in a new string.
The method takes 2 parameters: the start position, and the end position (end not included).
Example
Slice out a portion of a string from position 7 to position 13 (13 not included):
let str = "Apple, Banana, Kiwi";
let part = str.slice(7, 13);
Note: JavaScript counts positions from zero. First position is 0. Second position is 1.
If a parameter is negative, the position is counted from the end of the string.
This example slices out a portion of a string from position -12 to position -6:
Example
let str = "Apple, Banana, Kiwi";
let part = str.slice(-12, -6);
If you omit the second parameter, the method will slice out the rest of the string:
Example
let part = str.slice(7);
or, counting from the end:
Example
let part = str.slice(-12);
JavaScript String substring()
substring()
is similar to slice()
.
The difference is that start and end values less than 0 are treated as 0 in substring()
.
Example
let str = "Apple, Banana, Kiwi";
let part = str.substring(7, 13);
If you omit the second parameter, substring()
will slice out the rest of the string.
JavaScript String substr()
substr()
is similar to slice()
.
The difference is that the second parameter specifies the length of the extracted part.
Example
let str = "Apple, Banana, Kiwi";
let part = str.substr(7, 6);
If you omit the second parameter, substr()
will slice out the rest of the string.
Example
let str = "Apple, Banana, Kiwi";
let part = str.substr(7);
If the first parameter is negative, the position counts from the end of the string.
Example
let str = "Apple, Banana, Kiwi";
let part = str.substr(-4);
Replacing String Content
The replace()
method replaces a specified value with another value in a string:
Example
let text = "Please visit Microsoft!";
let newText = text.replace("Microsoft", "apostube");
Note:
- The
replace()
method does not change the string it is called on. - The
replace()
method returns a new string. - The
replace()
method replaces only the first match - If you want to replace all matches, use a regular expression with the /g flag set. See examples below.
By default, the replace()
method replaces only the first match:
Example
let text = "Please visit Microsoft and Microsoft!";
let newText = text.replace("Microsoft", "apostube");
By default, the replace()
method is case sensitive. Writing MICROSOFT (with upper-case) will not work:
Example
let text = "Please visit Microsoft!";
let newText = text.replace("MICROSOFT", "apostube");
To replace case insensitive, use a regular expression with an /i
flag (insensitive):
Example
let text = "Please visit Microsoft!";
let newText = text.replace(/MICROSOFT/i, "apostube");
To replace all matches, use a regular expression with a /g
flag (global match):
Example
let text = "Please visit Microsoft and Microsoft!";
let newText = text.replace(/Microsoft/g, "apostube");
Converting to Upper and Lower Case
A string is converted to upper case with toUpperCase()
:
A string is converted to lower case with toLowerCase()
:
JavaScript String toUpperCase()
Example
let text1 = "Hello World!";
let text2 = text1.toUpperCase();
JavaScript String toLowerCase()
Example
let text1 = "Hello World!"; // String
let text2 = text1.toLowerCase(); // text2 is text1 converted to lower
JavaScript String concat()
concat()
joins two or more strings:
Example
let text1 = "Hello";
let text2 = "World";
let text3 = text1.concat(" ", text2);
The concat()
method can be used instead of the plus operator. These two lines do the same:
Example
text = "Hello" + " " + "World!";
text = "Hello".concat(" ", "World!");
JavaScript String trim()
The trim()
method removes whitespace from both sides of a string:
Example
let text1 = " Hello World! ";
let text2 = text1.trim();
JavaScript String Padding
ECMAScript 2017 added two String methods: padStart()
and padEnd()
to support padding at the beginning and at the end of a string.
JavaScript String padStart()
The padStart()
method pads a string with another string:
Example
let text = "5";
let padded = text.padStart(4,"x");
Example
let text = "5";
let padded = text.padStart(4,"0");
Example
let numb = 5;
let text = numb.toString();
let padded = text.padStart(4,"0");
JavaScript String padEnd()
The padEnd()
method pads a string with another string:
Example
let text = "5";
let padded = text.padEnd(4,"x");
Example
let text = "5";
let padded = text.padEnd(4,"0");
Example
let numb = 5;
let text = numb.toString();
let padded = text.padEnd(4,"0");
Extracting String Characters
There are 3 methods for extracting string characters:
charAt(position)
charCodeAt(position)
- Property access [ ]
JavaScript String charAt()
The charAt()
method returns the character at a specified index (position) in a string:
Example
let text = "HELLO WORLD";
let char = text.charAt(0);
JavaScript String charCodeAt()
The charCodeAt()
method returns the unicode of the character at a specified index in a string:
The method returns a UTF-16 code (an integer between 0 and 65535).
Example
let text = "HELLO WORLD";
let char = text.charCodeAt(0);
Property Access
ECMAScript 5 (2009) allows property access [ ] on strings:
Example
let text = "HELLO WORLD";
let char = text[0];
Note:
Property access might be a little unpredictable:
- It makes strings look like arrays (but they are not)
- If no character is found, [ ] returns undefined, while charAt() returns an empty string.
- It is read only. str[0] = “A” gives no error (but does not work!)
Example
let text = "HELLO WORLD";
text[0] = "A"; // Gives no error, but does not work
Converting a String to an Array
If you want to work with a string as an array, you can convert it to an array.
JavaScript String split()
A string can be converted to an array with the split()
method:
Example
text.split(",") // Split on commas
text.split(" ") // Split on spaces
text.split("|") // Split on pipe
If the separator is omitted, the returned array will contain the whole string in index [0].
If the separator is “”, the returned array will be an array of single characters:
Example
text.split("")
41 Responses
buy levofloxacin 250mg generic buy generic levaquin
dutasteride ca flomax 0.2mg ca order zofran 8mg generic
spironolactone tablet valtrex 500mg canada fluconazole 200mg cost
buy acillin online ampicillin 500mg oral erythromycin 250mg pill
fildena 100mg brand purchase robaxin online cheap robaxin 500mg brand
order sildenafil generic order generic estrace 2mg generic estradiol 2mg
buy lamictal 50mg sale order generic vermox tretinoin brand
tadalafil 10mg brand avanafil pill order diclofenac without prescription
isotretinoin 10mg oral amoxil uk azithromycin online
order tadalafil online cheap cialis 20 mg peak time cheap viagra tablets
buy arimidex 1mg without prescription best viagra online pharmacy sildenafil 50mg usa
order deltasone 5mg generic order deltasone 40mg pills sildenafil 100mg tablets
tadalafil 20mg generika rezeptfrei kaufen viagra 50mg kaufen ohne rezept original sildenafil 50mg rezeptfrei sicher kaufen
accutane 40mg uk buy stromectol for sale ivermectin 3mg for people
provigil 200mg us acetazolamide oral diamox generic
order generic doxycycline order clomiphene 100mg generic order lasix 40mg pills
buy ramipril 10mg online order avapro 150mg sale order azelastine 10 ml generic
buy catapres buy minocycline without prescription order spiriva 9 mcg pill
buspar generic order buspar 10mg without prescription ditropan online order
order hytrin 5mg buy sulfasalazine online purchase azulfidine pill
alendronate 70mg cost famotidine for sale online pepcid 20mg pills
buy olmesartan 20mg without prescription olmesartan 10mg pill order diamox 250 mg pills
cost tacrolimus ropinirole order order urso 300mg without prescription
isosorbide 40mg for sale buy lanoxin 2250 mg pill buy micardis 20mg for sale
bupropion 150mg price buy strattera for sale order quetiapine 100mg pills
buy molnupiravir 200 mg without prescription cefdinir 300mg drug order prevacid 30mg without prescription
buy zoloft 50mg without prescription Buy viagra canada order viagra 100mg sale
order salbutamol 100mcg online pfizer viagra buy generic viagra 100mg
tadalafil brand name levitra vs viagra dosage sildenafil 100mg pills for sale
cialis 5mg price cheap cialis for sale amantadine 100 mg generic
purchase naltrexone pills buy naltrexone pill abilify price
buy avlosulfon 100mg without prescription nifedipine 30mg brand order perindopril 4mg
purchase provera generic buy microzide 25 mg online cheap periactin 4mg usa
provigil 100mg cost canada pharmacy buy ivermectin uk
fluvoxamine 100mg pill cymbalta 20mg brand order glucotrol 10mg generic
buy accutane 40mg generic order amoxicillin 250mg order prednisone 40mg
generic nootropil 800mg buy nootropil without prescription cheap viagra for sale
brand azithromycin order zithromax 250mg without prescription order neurontin 600mg generic
cialis us order tadalafil 20mg sildenafil 200mg
purchase lasix online cheap hydroxychloroquine price plaquenil 400mg tablet
tadalafil 10mg us buy anafranil 25mg generic anafranil 50mg price