27.4 C
Gujarat
HomeJavascriptStrings in javascript

Strings in javascript

Strings in javascript post


A JavaScript string is zero or more characters written inside quotes.JavaScript strings are used for storing and manipulating text. You can use single or double quotes.

var myName="patel";

var myname='rocoderes'

Strings can be created as primitives, from string literals, or as objects, using the String() constructor.



let myName = new String('patel');

πŸ‘‰ How to find the length of a string

       String.length
Reflects the length of the string.

Example:


let myName = 'Rocoderes';
console.log(myName.length);

output:


PS C:UsersThe-BeastDesktopjavascript Blog> node index.js       
9

PS C:UsersThe-BeastDesktopjavascript Blog>

1)Escape Character


let anySentence = 'We are the so-called "Vikings" from the north.';

console.log(anySentence);


let anySentence = " We are the so-called 'Vikings' from the north. ";
console.log(anySentence);

output:


PS C:UsersThe-BeastDesktopjavascript Blog> node index.js       
 We are the so-called 'Vikings' from the north. 

PS C:UsersThe-BeastDesktopjavascript Blog>

2) Finding a String in a String

1)String.indexOf(searchValue ,[fromIndex]) 

The indexOf() method returns the index of (the position of) the first occurrence of a specified text in a string.

Example:


const myBioData = 'Hello From The Rocoderes';
console.log(myBioData.indexOf('o', 5));

output:


PS C:UsersThe-BeastDesktopjavascript Blog> node index.js 
8

PS C:UsersThe-BeastDesktopjavascript Blog>

2)String.lastIndexOf(searchValue ,[fromIndex])

Returns the index within the calling String object of the last occurrence of searchValue, or -1 if not found.

Example:


const myBioData = 'hello world from the rocodres';
console.log(myBioData.lastIndexOf('o', 6));

output:


PS C:UsersThe-BeastDesktopjavascript Blog> node index.js 
4
PS C:UsersThe-BeastDesktopjavascript Blog> 

3)Searching for a String in a String

String.search(regexp)

πŸ‘‰The search() method searches a string for a specified value and returns the position of the match.
πŸ‘‰The search() method cannot take a second start position argument.
πŸ‘‰This method returns -1 if no match is found.

Example:


const myBioData = 'Hello From The Rocodres';
let sData = myBioData.search('Rocodres');
console.log(sData);

output:


PS C:UsersThe-BeastDesktopjavascript Blog> node index.js 
15
PS C:UsersThe-BeastDesktopjavascript Blog> 

πŸ‘‰Perform a case-sensitive search:


const myBioData = 'Hello From The Rocodres';
let sData = myBioData.search('rocodres');
console.log(sData);

output:


PS C:UsersThe-BeastDesktopjavascript Blog> node index.js 
-1
PS C:UsersThe-BeastDesktopjavascript Blog> 

4) Extracting String Parts

πŸ‘‰There are 3 methods for extracting a part of a string:
1)slice(start, end)
2)substring(start, end)
3)substr(start, length)

1)slice() Method

πŸ‘‰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).
πŸ‘‰The slice() method selects the elements starting at the given start argument, and ends at, but does not include, the given end argument.
πŸ‘‰ Note: The original array will not be changed.
πŸ‘‰ Remember: JavaScript counts positions from zero. First position is 0.

Example:


var str = 'Apple, Bananaa, Kiwi, mango';

let res = str.slice(0, 4);
console.log(res);

output:


PS C:UsersThe-BeastDesktopjavascript Blog> node index.js 
Appl
PS C:UsersThe-BeastDesktopjavascript Blog> 

Example:


var fruits = [ 'Banana', 'Orange', 'Lemon', 'Apple', 'Mango' ];
var res = fruits.slice(1, 3);
console.log(res);

output:


PS C:UsersThe-BeastDesktopjavascript Blog> node index.js 
[ 'Orange', 'Lemon' ]
PS C:UsersThe-BeastDesktopjavascript Blog> 

Example:


var fruits = [ 'Banana', 'Orange', 'Lemon', 'Apple', 'Mango' ];
var res = fruits.slice(-4, -1);
console.log(res);

output:


PS C:UsersThe-BeastDesktopjavascript Blog> node index.js 
[ 'Orange', 'Lemon', 'Apple' ]
PS C:UsersThe-BeastDesktopjavascript Blog>

Example:


var str = 'Apple, Bananaa, Kiwi, mango';
let res = str.slice(7);
console.log(res);

output:


PS C:UsersThe-BeastDesktopjavascript Blog> node index.js 
Bananaa, Kiwi, mango
PS C:UsersThe-BeastDesktopjavascript Blog> 

2)substring() Method

πŸ‘‰ substring() is similar to slice().
πŸ‘‰ The difference is that substring() cannot accept negative indexes.

Example:


var str = 'Apple, Bananaa, Kiwi';
let res = str.substring(1, 8);
console.log(res);

output:


PS C:UsersThe-BeastDesktopjavascript Blog> node index.js 
pple, B
PS C:UsersThe-BeastDesktopjavascript Blog> 
πŸ‘‰ If we give negative value then the characters are counted from the 0th pos

var str = 'Hello world!';
var res = str.substring(-2, 8);
console.log(res);

output:


PS C:UsersThe-BeastDesktopjavascript Blog> node index.js 
Hello wo
PS C:UsersThe-BeastDesktopjavascript Blog> 

3)The substr() Method

πŸ‘‰  substr() is similar to slice().
πŸ‘‰ The difference is that the second parameter specifies the length of the extracted part.
πŸ‘‰ Note: The substr() method does not change the original string.

Example:


var str = 'Apple, Bananaa, Kiwi';
let res = str.substr(-4);
console.log(res);

//Extract parts of a string:
let res1 = str.substr(1, 5);
console.log(`Extract parts of a string: ${res1}`);

// Begin the extraction at position 4, and extract the rest of the string:
let res2 = str.substr(4);
console.log(`extract the rest of the string: ${res2}`);

//Extract only the first character:
let res3 = str.substr(0, 1);
console.log(`Extract only the first character: ${res3}`);

//Extract only the last character:
let res4 = str.substr(19, 1);
console.log(`Extract only the last character: ${res4}`);

output:


PS C:UsersThe-BeastDesktopjavascript Blog> node index.js 
Kiwi
Extract parts of a string: pple,
extract the rest of the string: e, Bananaa, Kiwi
Extract only the first character: A
Extract only the last character: i
PS C:UsersThe-BeastDesktopjavascript Blog> 

5)Replacing String Content

String.replace(searchFor, replaceWith)

πŸ‘‰ The replace() method replaces a specified value with another value in a string.
πŸ‘‰ The replace() method does not change the string.  It returns a new string.
πŸ‘‰ By default, the replace() method replaces only the first match
πŸ‘‰ By default, the replace() method is case-sensitive.

Example:


let originalData = 'Hello Friends visit the rocoderes';

let repalceData = originalData.replace('rocoderes', 'ROCODERES');
console.log(repalceData);
console.log(originalData);

output:


PS C:UsersThe-BeastDesktopjavascript Blog> node index.js 
Hello Friends visit the ROCODERES
Hello Friends visit the rocoderes
PS C:UsersThe-BeastDesktopjavascript Blog> 

6)Extracting String Characters

πŸ‘‰There are 3 methods for extracting string characters:
1) charAt(position)
2) charCodeAt(position)
3) Property access [ ]

1)The charAt() Method

πŸ‘‰ The charAt() method returns the character at a specified index (position) in a string.

Example:


let str = 'HELLO WORLD';

console.log(str.charAt(9));

output:


PS C:UsersThe-BeastDesktopjavascript Blog> node index.js 
L

PS C:UsersThe-BeastDesktopjavascript Blog>

2)The charCodeAt() Method

πŸ‘‰ 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).
πŸ‘‰ The Unicode Standard provides a unique number for every character, no matter the platform, device, application, or language. UTF-8 is a popular Unicode encoding which has 88-bit code units.

Example:


var str = 'HELLO WORLD';

console.log(str.charCodeAt(0));

output:


PS C:UsersThe-BeastDesktopjavascript Blog> node index.js 
72
PS C:UsersThe-BeastDesktopjavascript Blog> 

3)Property Access

πŸ‘‰ ECMAScript 5 (2009) allows property access [ ] on strings.

Example:


var str = 'HELLO WORLD';
console.log(str[1]);

output:


PS C:UsersThe-BeastDesktopjavascript Blog> node index.js 
E

PS C:UsersThe-BeastDesktopjavascript Blog>

πŸ™‹β€β™‚οΈ Other useful methods

Example:

let myName = 'HeLLo FrIEnds';
console.log(myName.toUpperCase());
console.log(myName.toLowerCase());

// The concat() Method πŸ™‹β€β™‚οΈ
// concat() joins two or more strings

let fName = 'Ro';
let lName = 'coderes';

console.log(fName + lName);
console.log(`${fName} ${lName}`);
console.log(fName.concat(lName));
console.log(fName.concat(' ', lName));

// String.trim() πŸ™‹β€β™‚οΈ
// The trim() method removes whitespace from both
// sides of a string

var str = '              Hello         World!            ';
console.log(str.trim());

// Converting a String to an Array
// A string can be converted to an array with the split()method

var txt = 'a, b,c d,e'; // String
console.log(txt.split(',')); // Split on commas

output:


PS C:UsersThe-BeastDesktopjavascript Blog> node index.js 
HELLO FRIENDS
hello friends       
Rocoderes
Ro coderes
Rocoderes
Ro coderes
Hello         World!
[ 'a', ' b', 'c d', 'e' ]

PS C:UsersThe-BeastDesktopjavascript Blog>


watch the video:https://youtu.be/KGkiIBTq0y0

RELATED ARTICLES

5 COMMENTS

  1. Howdy this is somewhat of off topic but I was wondering if blogs use WYSIWYG
    editors or if you have to manually code with HTML. I’m starting a blog soon but have no coding
    experience so I wanted to get advice from someone with experience.
    Any help would be greatly appreciated!

  2. Hello there! I could have sworn I’ve been to this site before but after
    browsing through some of the post I realized it’s new to me.
    Anyhow, I’m definitely delighted I found it and I’ll be bookmarking and
    checking back often!

  3. Howdy! Someone in my Facebook group shared this
    site with us so I came to take a look. I’m definitely enjoying
    the information. I’m bookmarking and will be tweeting this to my followers!

    Fantastic blog and terrific design.

  4. Oh my goodness! Awesome article dude! Thanks, However I am having difficulties with your RSS.
    I don’t know the reason why I am unable to subscribe to it.

    Is there anyone else having the same RSS issues? Anyone who knows the solution will you kindly respond?
    Thanks!!

  5. Howdy! Would you mind if I share your blog with my facebook group?
    There’s a lot of people that I think would really enjoy your content.

    Please let me know. Many thanks

LEAVE A REPLY

Please enter your comment!
Please enter your name here

15,000FansLike
5,000FollowersFollow
535FollowersFollow
- Advertisment -spot_img

Subscribe to our newsletter

To be updated with all the latest news, offers and special announcements.

Most Popular