之前在 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 中,我们分配一个字符串,该字符串使用分配给 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”,第二个字母是“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.
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中文网其他相关文章!