首頁 > web前端 > js教程 > 主體

JavaScript 基礎:第 2 部分

Mary-Kate Olsen
發布: 2024-10-01 20:19:30
原創
425 人瀏覽過

JavaScript Essentials: Part 2

之前在 JavaScript 基礎:第 1 部分中,我們從一些 javascript 資料型別開始,包括字串、數字、布林值和物件。在這一部分中,我們將更深入地研究:

  • 字串插值及其方法要點

字串插值

我們知道如何建立字串並將其列印出來。但是,我們如何使用字串中的變數來創建某種句子呢?這就是字串插值的全部內容。

範例

讓我們考慮這些變數。

const name = "John Doe";
const dateOfBirth = "2000-12-25";
const profession = "Software Engineer";
const numberOfPets = 2;
const weightOfProteinInGrams = 12.5;
const hasAJob = true;
登入後複製

我認為我們對上面的程式碼片段並不陌生。如果您不確定,請參閱 JavaScript 基礎知識:第 1 部分。

在字串插值中,我們使用反引號。是的,用於建立字串的反引號用於建立字串插值。如同前面提到的,我們要做的就是在字串中加入變數來建立句子。

const sentence = `Full name: ${name}, date of birth: ${dateOfBirth}, profession: ${profession}`;
console.log(sentence);
登入後複製

我們有一個名為 sentence 的字串變數。在 sentence 中,我們分配一個字串,該字串使用分配給 namedateOfBirth 的值。

字串插值是如何完成的很明顯嗎?它應該。我們將 ${name} 放在其中 name 是我們要加入字串變數中的變數(其值)。上面的範例使用 namedateOfBirth。為別人做事。

如果我們在需要的地方正確使用 plus 運算子進行字串連接,我們可能會得到相同的結果。

範例

由於我們正在建立一個字串,因此我們可以選擇任何我們喜歡的分隔符號。

const name = "John Doe";
const dateOfBirth = "2000-12-25";
const profession = "Software Engineer";
const numberOfPets = 2;
const weightOfProteinInGrams = 12.5;
const hasAJob = true;

const sentence =
  "Full name: " +
  name +
  ", date of birth: " +
  dateOfBirth +
  ", profession: " +
  profession;

console.log(sentence);
登入後複製

索引字串

您一定會聽到很多關於索引的內容。現在讓我們來談談它。如果有幫助的話,索引與下腳本相同。簡而言之,這意味著您可以使用字元的數字位置(索引,從零開始計數)從字串中尋找或檢索字元。我們將在處理數組時討論這個(索引)(同樣的想法也適用於數組)。

考慮字串“Doe”,第一個字母是“D”,第二個字母是“o”,第三個字母是“e”。在 javascript 中,索引從零開始,因此第一個字元(定位元素)位於索引 0,指向「D」。第二個將為 1,在索引 0 之後,它將指向“o”,然後索引 2 將指向最後一個(第三個)元素,即第三個位置的“e”字元。在 JavaScript 中,索引 = 元素位置 - 1。

範例

const someName = "Doe";

const firstChar = someName[0];
const secondChar = someName[1];
const thirdChar = someName[2];

console.log(
  `The characters in "${someName}" are: '${firstChar}', '${secondChar}' and '${thirdChar}'`
);
// The characters in "Doe" are: 'D', 'o' and 'e'
登入後複製

字串屬性和方法

字串是一個物件。這意味著它們有方法和屬性。方法是可以對字串物件執行的操作或函數。該字串物件具有屬性。現在,我們可以說屬性就像附加到該感興趣對象的變量,它保留有關同一對象的某些狀態(數據)。

我們研究一個名為 dot 運算子的新運算子。它用於存取物件的屬性和方法。

我們將查看常用的屬性和方法。我將屬性表示為 p,將方法表示為 m.

  • length (p): is a property that returns the number of characters in a string. Hence the length of the string.
  • toUpperCase() (m): is a method that returns the string in uppercase
  • toLowerCase() (m): is a method that returns the string in lowercase
  • endsWith(key: string) (m): is a method that returns true when the string ends with the key parameter (a string) else false
  • startsWith(key: string) (m): is a method that returns true when the string starts with the key parameter (a string) else false
  • includes(key: string) (m): is a method that returns true when the string contains the key string else false
  • replace(oldStr: string, withNewString: string) (m): is a method that replaces oldStr in the string with withNewString and returns the newly updated string
  • trim() (m): is a method that removes starting or ending white spaces of a string and returns a new value
  • split(key: string) (m): returns an array of the string where key is used as a divider (to split the string at the point)
  • substring(startingIndex: number, optionalEndingIndex?: number) (m): returns a position of a string specified by the _startingIndex_ to the character at the optionalEndingIndex, when provided.
  • indexOf(key: string, optionalKeySearchingStartingAtIndex?: number) (m): returns the position of the first occurrence of key. When optionalKeySearchingStartingAtIndex is provided, the searching starts there. If there key is not found, it returns -1
  • charAt(index: number) (m): returns the character at index or an empty string

Example
This is a whole single snippet in a single file, string_methods.js

// Using string methods and properties
const fullName = "John Doe";
登入後複製
  • Length
// NB: whatever method we can call on a string literal,
//we can do the same for a variable

// find and print out the length of the fullName string
// variable using the length property
const fullNameLength = fullName.length;

// using string interpolations here
console.log(`The name, "${fullName}", has ${fullNameLength} characters`);
登入後複製
  • To uppercase and lowercase
// counting includes the spaces and symbols too
// update the value of fullName and see what happens

// this is the same as above but I will encourage you
// to stick to string interpolations in cases like this
// console.log("The name, " + fullName + ", has " + fullNameLength + " characters");

// convert uppercase and lowercase
console.log(`Upper: ${fullName.toUpperCase()}`);
console.log(`Lower: ${fullName.toLowerCase()}`);
登入後複製
  • Starts and ends with
// check if fullName starts with John
const startsWithKey = "John";
const fullNameStartsWithJohn = fullName.startsWith(startsWithKey);
console.log(
  `It is ${fullNameStartsWithJohn} that "${fullName}" starts with "${startsWithKey}"`
);

const endsWithKey = "Doe";
const fullNameEndsWithDoe = fullName.endsWith(endsWithKey);
console.log(
  `It is ${fullNameEndsWithDoe} that "${fullName}" ends with "${endsWithKey}"`
);
登入後複製
  • includes
// try this yourself, check if fullName starts with john and doe,
// then uppercase and lowercase the key and try again (for both cases)

// check if fullName as a space
const fullNameHasASpace = fullName.includes(" ");
// here we passed the key/search string directly without creating a variable.
// I want you to know that we can also do that
console.log(`It is ${fullNameHasASpace} that "${fullName}" has a space`);
// we could have also done
// console.log(`It is ${fullName.includes(" ")} that "${fullName}" has a space`);
登入後複製
  • replace
// try checking if the fullName contains the letter J, either uppercase or lowercase
// how would you achieve this? refer to the methods above for clues, first

// replace Doe with Moe
const moedFullName = fullName.replace("Doe", "Moe");
console.log(`New full name: ${moedFullName}`);

// try replacing spaces with underscore
const stringWithStaringAndTrailingSpaces = " John Doe ";
console.log(
  stringWithStaringAndTrailingSpaces
    .replace(" ", "JS") // replaces the first " "
    .replace(" ", "_") // replaces the second " "
    .replace(" ", "TS") // replaces the third " "
);

// it replaces only one instance at a time. so it was chained.
// I don't have to create a temp variable

// trust me, having your users start their email with spaces is annoying
// and sometimes it's the input keyboard (I get it, I am just venting off)
// but then again it will not harm trimming the unnecessary (white) spaces
// we will trim the whites off the stringWithStaringAndTrailingSpaces
// we'd use another method to let you know that the trimming worked
console.log(
  `Length of original string: ${stringWithStaringAndTrailingSpaces.length}`
);
登入後複製
  • trim
console.log(
  `Length of trimmed string: ${
    stringWithStaringAndTrailingSpaces.trim().length
  }`
);
// remember the definition of the length, it counts the spaces too
登入後複製
  • split
// split is really useful, we can split the full name into the first
// and last name in order as is
// i don't think it will be pretty to have spaces with the names
// we'd do the splitting at the space
console.log(stringWithStaringAndTrailingSpaces.split(" "));
console.log(stringWithStaringAndTrailingSpaces.trim().split(" "));
// printing the split string (becomes an array) shows the content
// of the array (or string to be precise)
// note any difference? Would the assumption still hold that the
// first element (object) in the array will be the first name and
// second (which should be the last actually) is the last name?
// this doesn't hold anymore because of the starting and trailing spaces
登入後複製
  • substring
// substring(starting [, ending])
const someLongString = "This is some long string";
const substringFromTwoToEight = someLongString.substring(2, 8);
console.log(substringFromTwoToEight);
// is is

const substringFromStartToTwelve = someLongString.substring(0, 12);
console.log(substringFromStartToTwelve);
// This is some

const substringFromTenth = someLongString.substring(10);
console.log(substringFromTenth);
// me long string
登入後複製
  • indexOf
// chartAt and indexOf
const veryWeakPassword = "qwerty12";

const indexOfTee = veryWeakPassword.indexOf("t");
console.log(`The first 't' in "${veryWeakPassword}" is at index ${indexOfTee}`);
// The first 't' in "qwerty12" is at index 4

// Note that there is no 'v'
const indexOfVee = veryWeakPassword.indexOf("v");
console.log(`The first 'v' in "${veryWeakPassword}" is at index ${indexOfVee}`);
// The first 'v' in "qwerty12" is at index -1
登入後複製
  • chartAt
// based on the result of the above (using the indexOf Tee which was 4)
// let's find the value at index 4
const characterAtIndexFour = veryWeakPassword.charAt(4);
// we could have passed 'indexOfTee'
console.log(`The character at index '4' is '${characterAtIndexFour}'`);
// The character at index '4' is 't'

const characterAtIndexNegativeOne = veryWeakPassword.charAt(-1);
console.log(`The character at index '4' is '${characterAtIndexNegativeOne}'`);
// returns an empty string
// The character at index '4' is ''
登入後複製

Password and email validation

We have discussed a lot of concepts about strings here. There are a lot more. Practically, these are some of the (biasedly) frequently used methods. Let's create a script for password and email validation.

Password rules
Password must:

  • be six characters
  • start with uppercase p, 'P'
  • end with an underscore
  • have uppercase q, 'Q'
  • have lowercase r, 'r'
  • have its fifth character as uppercase v, 'V'

Email rules

Email must:

  • be at least sixteen characters
  • be in all lowercase
  • not have 'email' in it
  • not include an underscore
  • have one '@'
  • have one '.'
  • end with '.com'
  • have the character before the '@' to be the character, uppercase v, 'V'

It is simple actually. So let's do password validation together and you'd do the email verification.

Password validation

// password_verification.js
const veryWeakPassword = "qwerty12";
console.log(`Password validation for "${veryWeakPassword}"`);

// - be six characters
const passwordLength = veryWeakPassword.length;
console.log(
  `- Password must have 6 characters => "${veryWeakPassword}" has '${passwordLength}' characters`
);
// so it is a valid password based on our rules?

// - start with uppercase p, 'P'
const startsWithPee = veryWeakPassword.startsWith("P");
console.log(
  `- Password must start with 'P' => it is ${startsWithPee} that "${veryWeakPassword}" starts with 'P'`
);

// we can also check the first character, index 0.
const firstCharacter = veryWeakPassword[0];
console.log(
  `- Password must start with 'P' => "${veryWeakPassword}" starts with '${firstCharacter}'`
);

// - end with underscore
const endsWithUnderscore = veryWeakPassword.endsWith("_");
console.log(
  `- Password must end with '_' => it is ${endsWithUnderscore} that "${veryWeakPassword}" ends with '_'`
);

// from the index concept, the last character will be at index, length of string minus one
const lastCharacter = veryWeakPassword[veryWeakPassword.length - 1];
console.log(
  `- Password must start with 'P' => "${veryWeakPassword}" ends with '${lastCharacter}'`
);

// - have uppercase q, 'Q'
const hasUppercaseQue = veryWeakPassword.includes("Q");
console.log(
  `- Password must have uppercase q, 'Q' => it is ${hasUppercaseQue} that "${veryWeakPassword}" has 'Q'`
);

// we can use the index approach
const indexOfUppercaseQue = veryWeakPassword.indexOf("Q");
console.log(
  `- Password must have uppercase q, 'Q' => 'Q' is at index '${indexOfUppercaseQue}' of "${veryWeakPassword}"`
);
// we know that index -1 means, there 'Q' was not found

// - have lowercase r, 'r'
const hasLowercaseArr = veryWeakPassword.includes("r");
console.log(
  `- Password must have lowercase r, 'r' => it is ${hasLowercaseArr} that "${veryWeakPassword}" has 'r'`
);

// we can use the index approach too
const indexOfLowercaseArr = veryWeakPassword.indexOf("r");
console.log(
  `- Password must have lowercase r, 'r' => 'r' is at index '${indexOfLowercaseArr}' of "${veryWeakPassword}"`
);
// we know that index -1 means, there 'r' was not found

// - have its fifth character as uppercase v, 'V'
// fifth character with have index = fifth position - 1 = 4
// const fifthCharacter = veryWeakPassword[4]
const fifthCharacter = veryWeakPassword.charAt(4);
console.log(
  `- Password must have its fifth character as uppercase v, 'V' => "${veryWeakPassword}" has its 5th character as '${fifthCharacter}'`
);

// using the index approach, 'V' must have an index of 4 (same index logic as above)
const indexOfVee = veryWeakPassword.indexOf("V");
console.log(
  `- Password must have its fifth character as uppercase v, 'V' => 'V' is at index '${indexOfVee}' of "${veryWeakPassword}"`
);
登入後複製

Output from the console.log

Password validation for "qwerty12"
- Password must have 6 characters => "qwerty12" has '8' characters
- Password must start with 'P' => it is false that "qwerty12" starts with 'P'
- Password must start with 'P' => "qwerty12" starts with 'q'
- Password must end with '_' => it is false that "qwerty12" ends with '_'
- Password must start with 'P' => "qwerty12" ends with '2'
- Password must have uppercase q, 'Q' => it is false that "qwerty12" has 'Q'
- Password must have uppercase q, 'Q' => 'Q' is at index '-1' of "qwerty12"
- Password must have lowercase r, 'r' => it is true that "qwerty12" has 'r'
- Password must have lowercase r, 'r' => 'r' is at index '3' of "qwerty12"
- Password must have its fifth character as uppercase v, 'V' => "qwerty12" has its 5th character as 't'
- Password must have its fifth character as uppercase v, 'V' => 'V' is at index '-1' of "qwerty12"
登入後複製

Conclusion

String forms part of almost any data structure one would use. So knowing how to manipulate them gives you the upper hand.

Try your hands on the email verification and don't hesitate to share your implementation.

We have more on javascript to discuss such as:

  • Object
  • Arrays
  • Control structures (if statements, loops)
  • Functions
  • Callbacks, promises, async & await
  • Next big thing

以上是JavaScript 基礎:第 2 部分的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板