Tri načina naslova rečenice u JavaScript-u

Ovaj se članak temelji na skriptiranju osnovnog algoritma Free Code Camp, „ Naslov slučaja rečenica “.

U ovom algoritmu želimo promijeniti niz teksta tako da uvijek ima veliko slovo na početku svake riječi.

U ovom ću članku objasniti tri pristupa. Prvo s petljom FOR, drugo metodom map (), a treće metodom replace ().

Izazov algoritma

Vratite pruženi niz s prvim slovom svake velike riječi. Provjerite je li ostatak riječi malim slovima.

U svrhu ove vježbe, trebali biste također napisati velikim slovima povezujuće riječi poput "the" i "of".

Dati test slučajevi

  • titleCase ("Ja sam mali lonac za čaj") trebao bi vratiti niz.
  • titleCase ("Ja sam mali lonac za čaj") trebao bi vratiti "Ja sam mali lonac za čaj".
  • titleCase (“sHoRt AnD sToUt”) trebao bi vratiti “Short And Stout”.
  • titleCase („OVDJE JE MOJA RUČKA OVDJE JE MOJ IZLIV“) trebao bi vratiti „Ovdje je moja ručka Ovdje je moja cijev“.

1. Naslovni slučaj rečenica s petljom FOR

Za ovo rješenje koristit ćemo metodu String.prototype.toLowerCase (), metodu String.prototype.split (), metodu String.prototype.charAt (), metodu String.prototype.slice () i Array. prototype.join () metoda.

  • Metoda toLowerCase () vraća vrijednost pozivnog niza pretvorenu u mala slova
  • Metoda split () razdvaja objekt String u niz nizova odvajanjem niza u podnizove.
  • Metoda charAt () vraća navedeni znak iz niza.
  • Metoda slice () izdvaja odjeljak niza i vraća novi niz.
  • Metoda join () spaja sve elemente niza u niz.

Trebat ćemo dodati prazan prostor između zagrada metode split () ,

var strSplit = "I'm a little tea pot".split(' ');

koji će iznijeti niz odvojenih riječi:

var strSplit = ["I'm", "a", "little", "tea", "pot"];

Ako ne dodate razmak u zagradi, imat ćete ovaj izlaz:

var strSplit = ["I", "'", "m", " ", "a", " ", "l", "i", "t", "t", "l", "e", " ", "t", "e", "a", " ", "p", "o", "t"];

Spojit ćemo se

str[i].charAt(0).toUpperCase()

- koji će velikim slovima upisati znak 0 trenutnog niza u petlji FOR -

i

str[i].slice(1)

- koji će se izdvojiti iz indeksa 1 do kraja niza.

Cijeli ćemo niz postaviti u mala slova u svrhu normalizacije.

S komentarima:

 function titleCase(str) { // Step 1. Lowercase the string str = str.toLowerCase(); // str = "I'm a little tea pot".toLowerCase(); // str = "i'm a little tea pot"; // Step 2. Split the string into an array of strings str = str.split(' '); // str = "i'm a little tea pot".split(' '); // str = ["i'm", "a", "little", "tea", "pot"]; // Step 3. Create the FOR loop for (var i = 0; i  "I'm A Little Tea Pot" } titleCase("I'm a little tea pot");

Bez komentara:

function titleCase(str) { str = str.toLowerCase().split(' '); for (var i = 0; i < str.length; i++) { str[i] = str[i].charAt(0).toUpperCase() + str[i].slice(1); } return str.join(' '); } titleCase("I'm a little tea pot");

2. Naslov Slučaj i rečenica Metoda karte ()

Za ovo rješenje koristit ćemo metodu Array.prototype.map ().

  • Metoda map () stvara novi niz s rezultatima pozivanja zadane funkcije na svakom elementu u ovom nizu. Korištenje mape pozvat će pruženu funkciju povratnog poziva jednom za svaki element u nizu, redom, i iz rezultata konstruira novi niz.

Prije početka primjene metode map (), mi ćemo malim i malim slovima podijeliti niz kao što je prikazano u prethodnom primjeru.

Umjesto da koristimo FOR petlju, primijenit ćemo metodu map () kao uvjet na istoj povezanosti iz prethodnog primjera.

(word.charAt(0).toUpperCase() + word.slice(1));

S komentarima:

 function titleCase(str) { // Step 1. Lowercase the string str = str.toLowerCase() // str = "i'm a little tea pot"; // Step 2. Split the string into an array of strings .split(' ') // str = ["i'm", "a", "little", "tea", "pot"]; // Step 3. Map over the array .map(function(word) { return (word.charAt(0).toUpperCase() + word.slice(1)); /* Map process 1st word: "i'm" => (word.charAt(0).toUpperCase() + word.slice(1)); "i'm".charAt(0).toUpperCase() + "i'm".slice(1); "I" + "'m"; return "I'm"; 2nd word: "a" => (word.charAt(0).toUpperCase() + word.slice(1)); "a".charAt(0).toUpperCase() + "".slice(1); "A" + ""; return "A"; 3rd word: "little" => (word.charAt(0).toUpperCase() + word.slice(1)); "little".charAt(0).toUpperCase() + "little".slice(1); "L" + "ittle"; return "Little"; 4th word: "tea" => (word.charAt(0).toUpperCase() + word.slice(1)); "tea".charAt(0).toUpperCase() + "tea".slice(1); "T" + "ea"; return "Tea"; 5th word: "pot" => (word.charAt(0).toUpperCase() + word.slice(1)); "pot".charAt(0).toUpperCase() + "pot".slice(1); "P" + "ot"; return "Pot"; End of the map() method */ }); // Step 4. Return the output return str.join(' '); // ["I'm", "A", "Little", "Tea", "Pot"].join(' ') => "I'm A Little Tea Pot" } titleCase("I'm a little tea pot");

Bez komentara:

function titleCase(str) { return str.toLowerCase().split(' ').map(function(word) { return (word.charAt(0).toUpperCase() + word.slice(1)); }).join(' '); } titleCase("I'm a little tea pot");

3. Naslov Slučaj i rečenica Uz metode karte () i replace ()

Za ovo rješenje nastavit ćemo koristiti metodu Array.prototype.map () i dodati metodu String.prototype.replace ().

  • The replace() method returns a new string with some or all matches of a pattern replaced by a replacement.

In our case, the pattern for the replace() method will be a String to be replaced by a new replacement and will be treated as a verbatim string. We can also use a regular expression as the pattern to solve this algorithm.

We will lowercase and split the string as seen in the first example before applying the map() method.

With comments:

 function titleCase(str) { // Step 1. Lowercase the string str = str.toLowerCase() // str = "i'm a little tea pot"; // Step 2. Split the string into an array of strings .split(' ') // str = ["i'm", "a", "little", "tea", "pot"]; // Step 3. Map over the array .map(function(word) { return word.replace(word[0], word[0].toUpperCase()); /* Map process 1st word: "i'm" => word.replace(word[0], word[0].toUpperCase()); "i'm".replace("i", "I"); return word => "I'm" 2nd word: "a" => word.replace(word[0], word[0].toUpperCase()); "a".replace("a", "A"); return word => "A" 3rd word: "little" => word.replace(word[0], word[0].toUpperCase()); "little".replace("l", "L"); return word => "Little" 4th word: "tea" => word.replace(word[0], word[0].toUpperCase()); "tea".replace("t", "T"); return word => "Tea" 5th word: "pot" => word.replace(word[0], word[0].toUpperCase()); "pot".replace("p", "P"); return word => "Pot" End of the map() method */ }); // Step 4. Return the output return str.join(' '); // ["I'm", "A", "Little", "Tea", "Pot"].join(' ') => "I'm A Little Tea Pot" } titleCase("I'm a little tea pot");

Without comments:

function titleCase(str) { return str.toLowerCase().split(' ').map(function(word) { return word.replace(word[0], word[0].toUpperCase()); }).join(' '); } titleCase("I'm a little tea pot");

I hope you found this helpful. This is part of my “How to Solve FCC Algorithms” series of articles on the Free Code Camp Algorithm Challenges, where I propose several solutions and explain step-by-step what happens under the hood.

Three ways to repeat a string in JavaScript

In this article, I’ll explain how to solve freeCodeCamp’s “Repeat a string repeat a string” challenge. This involves…

Two ways to confirm the ending of a String in JavaScript

In this article, I’ll explain how to solve freeCodeCamp’s “Confirm the Ending” challenge.

Three Ways to Reverse a String in JavaScript

This article is based on Free Code Camp Basic Algorithm Scripting “Reverse a String”

Three Ways to Factorialize a Number in JavaScript

This article is based on Free Code Camp Basic Algorithm Scripting “Factorialize a Number”

Two Ways to Check for Palindromes in JavaScript

This article is based on Free Code Camp Basic Algorithm Scripting “Check for Palindromes”.

Three Ways to Find the Longest Word in a String in JavaScript

This article is based on Free Code Camp Basic Algorithm Scripting “Find the Longest Word in a String”.

Three ways you can find the largest number in an array using JavaScript

In this article, I’m going to explain how to solve Free Code Camp’s “Return Largest Numbers in Arrays” challenge. This…

If you have your own solution or any suggestions, share them below in the comments.

Or you can follow me on Medium, Twitter, Github and LinkedIn.

‪#‎StayCurious‬, ‪#‎KeepOnHacking‬ & ‪#‎MakeItHappen‬!

Resources

  • toLowerCase() method — MDN
  • toUpperCase() method — MDN
  • charAt() method — MDN
  • slice() method — MDN
  • split() method — MDN
  • join() method — MDN
  • for — MDN
  • map() method — MDN
  • replace() method — MDN