This post will describe about string methods in JavaScript.
Before learning string methods take an overview of JavaScript string.
JavaScript string methods |
What is JavaScript string?
JS string is zero or more characters, which also value of variable written in single or double quotes.
For example,
let a=”Hello”; //Hello let b=’Good morning!’; //Good morning! let c=”How are you?,’John’”; // How are you?,'John' let d=’What is “programming language”?’; // What is “programming language”?
Note::-
When quotes are also used inside string, write different quotes because similar quotes used for inside string cause an error.
For example,
let t=”How are you?,”John””; // Uncaught syntax error: Unexpected identifier.
Use backslash \’ or \” instead.
let t=”How are you?,/”John Doe/””; // How are you?,”John Doe”
How to find length of string?
Built-in property length is used for calculate length of string in JavaScript.
Below example returns string with its length in number.
let c=”How are you?,’John’”; let l=c.length; document.write(l); //19
Javascript also counts special characters and white space in length.
Now moving on string methods.
JavaScript String methods
1) slice()
It extracts part of string from specified position and returns this extracted part of string in new string.
Syntax
slice(start_position,end_position)
The extraction of string strat from 'start_position’ and end up at ending position (the ending position is not included in extraction part).
Example :- Display only javascript from string.
let str="Welcome to javascript"; let res=str.slice(11,21); document.write(res); // javascript
Remember:-
In JavaScript position of character starts from 0, means position of ‘W’ is 0, ‘e’ becomes 1st position. The ‘javascript’ position starts from 11 and ended with 20, but javascript eliminate last position so here as a last position 21 is taken.
- If negative values passed, character position count start from end of the string.
let str="Welcome to javascript"; let res=str.slice(-21,-14); document.write(res); //Welcome
The count start from last character ‘t’ and ended at ‘W’. The word ‘Welcome’ position in reverse is -14 to -21.
If second parameter is omitted rest of the string will return.
2) substring()
It works similar as slice() method.
Syntax
No string return in output.
substring(start_position,end_position)
Example
let str=”Welcome to javascript”; let s=str.substring(11,21); document.write(s); // javascript
There is a one difference between two, If you specify negative values in substring() method ,it will treated as 0 and nothing will return.
Example
let s=str.substring(-21,-14);
3) substr()
The substr() also work similar as above two methods but it returns length of extracted part of string too.
Syntax
substr(start_position, length)
The second parameter length specifies length of extracted part of string.
Example
Returns ‘to’ at position 8 with length of 2 character.
let str="Welcome to javascript"; let sub=str.substr(8,2); document.write(sub); // to
- If only one parameter is specified, rest of the string will return.
- If negative values passed, position count from end of the string.
get only 10 characters from string.
let st="javascript programing"; let r=st.substr(11,10); document.write(r); //programing
In output 10 characters string at 11 position.
4) replace()
The replace() method replaces specified string with new string.
Syntax
replace(“specified_string”,”new_string”)
Example
Replaces string “javascript” with new string “html”.
let str=”Welcome to javascript”; let n= str.replace("javascript","html"); document.write(n); //Welcome to html
Points to remember:-
• replace() method is replaces only first match. For example in above example if the word javascript repeats two or more times than it only replace the first one.
• replace() method is case-sensitive, so always write matching case otherwise use regular expression /i flag.
str=”Welcome to javascript & javascript”; let n=str.replace(/JavaScript/i,”html”); document.write(n); // Welcome to html & javascript
Example
replace string with ’***'(asterisk).
let repst="Stars in the sky"; let rep=repst.replace("Stars","*****"); document.write(rep); // ***** in the sky
5) replaceAll()
The replaceAll() method is introduced by ESMA script in 2021.
It replaces all the string which matches with specified string or regular expression and returns new string. The original string remain as it is. In regular expression always use '/g’ flag otherwise replaceAll() method returns error.
Syntax
string.replaceAll(reg_expression|string , replacement_string|function)
Example
Replace whitespace with _ using regular expression.
let a=”trin trin trin bell is ringing!!”; let res=a.replaceAll(/\s/g,’_'); document.write(res); //trin_trin_trin_bell_is_ ringing!!
Example
Replace string “apple” with new string “strawberry”.
let b=”apple,banana,cherry,apple,mango,apple”; let c=b.replaceAll(“apple”,”strawberry”); document.write(c); //strawberry,banana,cherry,strawberry,mango,strawberry
6) toUpperCase()
It converts lower case character to upper case character.
Example
let uc=”JavaScript”; let txt=uc.toUpperCase(); document.write(txt); // JAVASCRIPT
7) toLowerCase()
It converts upper case character to lower case character.
Example
let uc="JavaScript"; let txt=uc.toLowerCase(); document.write(txt); // javascript
8) concat()
The concat() method merge two or more strings.
Example
let s1="web"; let s2="design"; let mg=s1.concat(" ",s2); document.write(mg); //web design
9) trim()
It removes white space from beginning and ending of the string.
It not remove white space from middle.
Example
let t=" scripting language "; let tr=t.trim(); document.write(tr); //scripting language
10) trimStart()
It removes whitespace only from beginning of the string. This method added in ESMA script in 2019.
Example
let a=" Hello programmers!! "; let b=a.trimStart(); alert(a);// Hello programmers!! alert(b);//Hello programmers!!
document.write("String length=",a.length,"<br>");//String length=34
document.write("String length=",b.length);//String length=26
11) trimEnd()
It removes whitespace only from ending of the string. This method is also added in ESMA script in 2019.
Example
let a=" Hello programmers!! "; let b=a.trimEnd(); alert(a);// Hello programmers!! alert(b);// Hello programmers!! document.write("String length=",a.length,"<br>");//String length=34 document.write("String length=",b.length);//String length=27
12) padStart()
It add new string or character at beginning of another string.
Syntax
padStart (no_of_character, string|character )
Example
String “good” padded at beginning of string “morning”.
let greet="morning"; let padst=greet.padStart(12,"good "); document.write(padst); // good morning
(total characters including white space is 12)
13) padEnd()
It adds new string or character at ending of string.
Syntax
padEnd (no_of_character, string|character )
Example
let greet="good"; let padend=greet.padEnd(12," morning"); document.write(padend); // good morning
14) charAt()
It returns single character at specified position.
Syntax
charAt(character_position)
Example
let text="Hello mario"; let retxt=text.charAt(6); document.write(retxt); //m Position of character ‘m’ in string is 6.(counting starts from 0)
15) charCodeAt()
It returns unicode (encoding format:UTF-16 code) of character at specified position.
Syntax
charCodeAt (character _position)
Example returns encoded character of string
let text="Hello mario"; let code=text.charCodeAt(6); document.write(code); //109
Character ‘m’ unicode value is 109.
16) split()
It converts string into an array.
Syntax
split(where_to_seperate)
Example
Returns comma separated single character array
let text="Hello mario"; let splt=text.split(""); document.write(splt); // H,e,l,l,o, ,m,a,r,i,o
Example
Returns two string array
let text="Hello mario"; let splt=text.split(" "); //separate at space document.write(splt); //Hello,mario
Example
Returns array seperated at '|'
let text="Hello|ma|rio"; let splt=text.split("|"); document.write(splt); //Hello,ma,rio
Word, Character & line counter
This is mini project created with JavaScript string methods.
The split () method and length property are used for counting.
Code:
HTML
<!DOCTYPE html> <html> <head> <title>character word line counter</title> </head> <body> <div class="main"> <h1>Word Character & line Counter</h1> <label for="stringcount">Enter your text:</label> <br> <textarea id="chars" rows=10 cols=35></textarea><br> <button onClick="charcount()">Count</button> <div class="res"> <p>Characters : <span id="count">0</span></p> <p>Words :<span id="wrdcnt">0</span></p> <p>Lines :<span id="linecnt">0</span></p> </div> </div> </body> </html>
CSS
.main { height:auto; width:400px; background-color:#030303; color:#00ff66; } h1,label,textarea { padding:10px; } h1 { text-align:center; } label,textarea,button { margin:20px; } label { margin-left:40px; } textarea { margin-left:50px; border-radius:10px; border: 5px double #c3c3c3; outline:none; font-family:Georgia,serif; } button { width:50%; height:50px; border-radius:20px; font-size:20pt; color:#fcfcfc; background-color:transparent; margin-left:95px; border:2px solid #f2f2f2; } button:hover { background-color:#226666; } p { position:relative; padding:10px; display:inline-block; margin-left:10px; font:16pt bold; } span { color:#ff0033; }
Javascript
function charcount() { let a=document.getElementById("chars").value; let cnt=a.length; document.getElementById("count").innerHTML=cnt; let wrd=a.split(/\s/).length; document.getElementById("wrdcnt").innerHTML=wrd; let line=a.split(/\n/).length; document.getElementById("linecnt").innerHTML=line; }
Output of word, character and line counter
Summary
This post covered string methods.
remember some points about the string and string methods
- All strings are immutable, they cannot be modified but replaced.
- All string methods returns new string.
- In JavaScript counting of position starts from 0.
0 Comments