JS - 문자열 프리미티브에 관한 모든 것

WBOY
풀어 주다: 2024-08-28 06:11:33
원래의
919명이 탐색했습니다.

JS - All about String Primitive

  • 문자열은 기본 요소이지만 여전히 객체에서 사용할 수 있는 메서드를 가지고 있습니다.
  • 문자열에 대한 메소드를 호출할 때마다 JS는 장면 뒤에서 String 기본 요소를 String 객체로 변환한 다음 메소드가 호출되는 해당 객체에 변환합니다. 이 프로세스를 박싱이라고 합니다. 문자열 프리미티브를 가져와서 상자 역할을 하는 String 객체 내부에 넣기 때문입니다. 즉, 문자열 프리미티브를 문자열 객체로 변환하는 "new String()" 메서드 내부에 인수를 전달합니다.
  • 작업이 완료되면 객체는 장면 뒤의 String 객체에서 String 기본 형식으로 다시 변환됩니다.
  • 'new String()'에 전달되는 모든 것은 typeof 연산자를 사용하여 확인할 수 있는 객체가 됩니다.
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';

로그인 후 복사

위 내용은 JS - 문자열 프리미티브에 관한 모든 것의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!