以前の JavaScript Essentials: Part 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 では、name と dateOfBirth に割り当てられた値を使用する文字列を割り当てます。
文字列補間がどのように行われたかは明らかですか?それはすべきです。 ${name} を入力します。name は文字列変数に追加する変数 (その値) です。上の例では、name と dateOfBirth を使用しています。他の人のために行動してください。
必要な場所で 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」、2 番目の文字は「o」、3 番目の文字は「e」です。 JavaScript ではインデックス付けは 0 から始まるため、最初の文字 (位置指定された要素) はインデックス 0 にあり、「D」を指します。 2 番目はインデックス 0 の後の 1 で、'o' を指し、次にインデックス 2 は最後の (3 番目) 要素、つまり 3 番目の位置の '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'
文字列はオブジェクトです。これは、メソッドとプロパティがあることを意味します。メソッドは、文字列オブジェクトに対して実行できるアクションまたは関数です。この文字列オブジェクトにはプロパティがあります。今のところ、プロパティは、この同じオブジェクトに関する何らかの状態 (データ) を保持する、対象のオブジェクトにアタッチされた変数のようなものであると言えます。
ドット 演算子と呼ばれる新しい演算子を見てみましょう。オブジェクトのプロパティとメソッドにアクセスするために使用されます。
頻繁に使用されるプロパティとメソッドを見ていきます。プロパティを p として、メソッドを m として示します。
Example
This is a whole single snippet in a single file, string_methods.js
// Using string methods and properties const fullName = "John Doe";
// 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`);
// 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()}`);
// 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}"` );
// 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`);
// 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}` );
console.log( `Length of trimmed string: ${ stringWithStaringAndTrailingSpaces.trim().length }` ); // remember the definition of the length, it counts the spaces too
// 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(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
// 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
// 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 ''
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:
Email rules
Email must:
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"
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:
以上がJavaScript の基礎: パート 2の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。