- String are primitives, still they have methods which are avaialable on objects.
- Whenever we call a method on string, JS converts the String primitive to String object behind the scene and then its on that object on which methods are called. This process is called boxing as String primitive is taken and put inside a String object acting as a box i.e it passes the argument inside the, "new String()" method converting a string primitive to a string object.
- When the operation is complete, object is converted back to String primitive from String object behind the scene.
- Anything which is passed into 'new String()' becomes an object which can be verified using typeof operator.
const car = 'Lamborghini Huracan EVO'; // Similarity of strings with arrays in JS car[0]; car[car.length-1]; car.length; // From begin car.indexOf('o'); car.indexOf('Huracan'); // From end car.lastIndexOf('E'); // index(begin, end) are used to extract part of string which are then passed to slice() as argument. car.slice(car.indexOf('o')); car.slice(8); car.slice(8,15); // Extracted string length will be (end-begin) as mentioned below // String are primitives, hence immutable. Always use a data-structure to return a new string after the operation. // Extract till a particular location inside an index. car.slice(0, car.indexOf(' ')); // Extract the last word. car.slice(car.lastIndexOf(' ')); // extracts along with space car.slice(car.lastIndexOf(' ') + 1); // +1 added to exclude the space // Extract from the end using negative values car.slice(-7); car.slice(1, -1); car.slice(0, -1); function knowYourSeatLocation(seat){ const x = seat.slice(-1); if(x === 'W'){ console.log("Window Seat"); } if(x === 'M'){ console.log("Middle Seat"); } if(x === 'A'){ console.log("Aisle Seat"); } } knowYourSeatLocation('43W'); knowYourSeatLocation('12A'); knowYourSeatLocation('67M'); // Common Methods: car.toLowerCase(); car.toUpperCase(); car.trim(); car.trimStart(); car.trimEnd(); // Methods returning boolean: Very good for conditional statements. car.includes('Lambo'); car.startsWith('Lam'); car.endsWith('EVO'); // On taking user i/p convert it to lowercase before performing any operations on the text. It would eliminate a lot of error sources related to letter-case. // Usage: Converting first letter to uppercase incase user enters name in mixed case to maintain consistency // Usage: Email validation for characters esp whitespace, invalid characters etc. // String replacement: (ToBeReplaced, ReplceWith) // replace() : A case-sensitive method. Immutable Methods for functional Programming: car.replace(' ','_'); car.replaceAll(' ','_'); // Using RegEx: Target text has to be enclosed between // with flag at the end. Desired text to be passed as second argument. car.replace(/ini/g,'123456'); // .split(): split the text based on condition, return the elements in the form of an array // .join(): opposite of .split() car.split(''); // as characters car.split(' '); // as words car.split('i'); // based on a character // Destrucutring makes it easier as compared to using .slice() const name = 'Peter Parker'; const [fName, lName] = name.split(' '); fName; lName; // Adding saluttations to the name: const title = ['Mr.', fName, lName.toUpperCase()].join(' '); title; // Usage: First letter of a Name capitalization const capitalizeName = function(name){ const names = name.split(' '); const namesUpper = []; for(const n of names){ // Method 1 and Method 2 are listed below in two lines. Both work. // namesUpper.push(n[0].toUpperCase() + n.slice(1)); namesUpper.push(n.replace(n[0],n[0].toUpperCase())); } console.log(namesUpper.join(' ')); }; capitalizeName('amar akbar anthony amarjeet'); // Padding a string i.e adding certain characters until a desired length is achieved. // (DesiredLength, ToBePaddedWith) const msg = 'Welcome to JS'; msg.padStart(20,'x'); msg.padEnd(20,'x'); // Convert a no into its string form by using: String() // Another way is to add an '' to a number i.e When one operand of a + sign is string, all operands are converted into string form. // Usage: Masking certain numbers of important documents const maskedId = function(id){ const str = id + ''; const lastFour = str.slice(-4); return lastFour.padStart(str.length, '*'); } maskedId(92837483297492); maskedId('r438t7h4irgrgTAFE'); // repeat(NoOfTimeToBeRepeated) : Repeat the same text multiple times const msgText = 'Raining.\n'; msgText.repeat(5 ); const TrainsWaiting = function(x){ console.log(`There are ${x} trains waiting on the station ${'?'.repeat(x)} \n`); } TrainsWaiting(4); TrainsWaiting(16); TrainsWaiting(8); // Extract string from a long text received from an API based on some separator found in text. const data = 'Departure';
The above is the detailed content of JS - All about String Primitive. For more information, please follow other related articles on the PHP Chinese website!

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

Bring matrix movie effects to your page! This is a cool jQuery plugin based on the famous movie "The Matrix". The plugin simulates the classic green character effects in the movie, and just select a picture and the plugin will convert it into a matrix-style picture filled with numeric characters. Come and try it, it's very interesting! How it works The plugin loads the image onto the canvas and reads the pixel and color values: data = ctx.getImageData(x, y, settings.grainSize, settings.grainSize).data The plugin cleverly reads the rectangular area of the picture and uses jQuery to calculate the average color of each area. Then, use

This article will guide you to create a simple picture carousel using the jQuery library. We will use the bxSlider library, which is built on jQuery and provides many configuration options to set up the carousel. Nowadays, picture carousel has become a must-have feature on the website - one picture is better than a thousand words! After deciding to use the picture carousel, the next question is how to create it. First, you need to collect high-quality, high-resolution pictures. Next, you need to create a picture carousel using HTML and some JavaScript code. There are many libraries on the web that can help you create carousels in different ways. We will use the open source bxSlider library. The bxSlider library supports responsive design, so the carousel built with this library can be adapted to any

Data sets are extremely essential in building API models and various business processes. This is why importing and exporting CSV is an often-needed functionality.In this tutorial, you will learn how to download and import a CSV file within an Angular


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version
Recommended: Win version, supports code prompts!

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),