codecamp

Useful string methods

先决条件: 基本的计算机素养,基本了解HTML和CSS,了解JavaScript是什么。
目的: 要理解字符串是对象,并学习如何使用这些对象上可用的一些基本方法来操作字符串。

字符串作为对象

我们之前已经说过,我们会再说一遍 - 是JavaScript中的一个对象。 当您创建字符串时,例如通过使用

var string = 'This is my string';

你的变量成为一个字符串对象实例,因此有大量的属性和方法可用。 如果您转到 字符串 / a>对象页面,并向下看页面上的列表!

现在,在你的大脑开始融化之前,不要担心!在你的学习之旅中,你真的不需要了解大部分时间。 但有一些,你可能会经常使用,我们会看看这里。

让我们在一个新的控制台中输入一些例子。 我们在下面提供了一个(您也可以 >在单独的标签或窗口中打开此控制台,或者如果愿意,可以使用浏览器开发者控制台)。

查找字符串的长度

这很简单 - 您只需使用 length 属性。 尝试输入以下行:

var browserType = 'mozilla';
browserType.length;

这很简单 - 您只需使用 length 属性。 尝试输入以下行:...

检索特定的字符串字符

在相关说明中,您可以使用方括号符号返回字符串中的任何字符 - 这意味着在变量名称的末尾包含方括号( [] ) 。 在方括号内包括您要返回的字符的编号,例如,检索您要执行的第一个字母:

browserType[0];

计算机从0计数,而不是1! 要检索任何字符串的最后一个字符,我们可以使用以下行,将此技术与上面查看的 length 属性结合使用:

browserType[browserType.length-1];

"mozilla"的长度是7,但是因为计数从0开始,字符位置是6,因此我们需要 length-1 。 例如,您可以使用它来查找一系列字符串的第一个字母,并按字母顺序排列。

在字符串中查找子字符串并提取它

  1. Sometimes you'll want to find if a smaller string is present inside a larger one (we generally say if a substring is present inside a string). This can be done using the indexOf() method, which takes a single parameter — the substring you want to search for. Try this:
    browserType.indexOf('zilla');
    This gives us a result of 2, because the substring "zilla" starts at position 2 (0, 1, 2  — so 3 characters in) inside "mozilla". Such code could be used to filter strings. For example, say we have a list of web addresses and only want to print out the ones that contain "mozilla".
  1. This can be done in another way, which is possibly even more effective. Try the following:
    browserType.indexOf('vanilla');
    This should give you a result of -1 — this is returned when the substring, in this case 'vanilla', is not found in the main string.

    You could use this to find all instances of strings that don't contain the substring 'mozilla', or do, if you use the negation operator, as shown below. You could do something like this:
    if(browserType.indexOf('mozilla') !== -1) {
      // do stuff with the string
    }
  2. When you know where a substring starts inside a string, and you know at which character you want it to end, slice() can be used to extract it. Try the following:
    browserType.slice(0,3);
    This returns "moz" — the first parameter is the character position to start extracting at, and the second parameter is the character position after the last one to be extracted. So the slice happens from the first position, up to, but not including, the last position.
     
  3. Also, if you know that you want to extract all of the remaining characters in a string after a certain character, you don't have to include the second parameter, rather, you only need to include the character position from where you want to extract the remaining characters in a string. Try the following:
    browserType.slice(2);
    This returns "zilla" — this is because the character position of 2 is the letter z, and because you didn't include a second parameter, the substring that was returned was all of the remaining characters in the string. 

注意: slice()的第二个参数是可选的:如果不包括它,片段将在原始字符串的末尾结束。 还有其他选择; 请研究 slice() 页面,看看你能找到什么。

更改案例

字符串方法 toLowerCase() >和 toUpperCase() 取字符串,并将所有字符分别转换为大写或小写。 例如,如果要在将所有用户输入的数据存储在数据库中之前对其进行规范化,这可能非常有用。

让我们尝试输入以下行,看看会发生什么:

var radData = 'My NaMe Is MuD';
radData.toLowerCase();
radData.toUpperCase();

更新字符串的部分

您可以使用 将字符串中的一个子字符串替换为另一个子字符串, replace() 方法。 这在一个基本层面非常简单,虽然有一些先进的东西,你可以做它,我们不会进入。

它需要两个参数 - 要替换的字符串,以及要替换的字符串。 试试这个例子:

browserType.replace('moz','van');

主动学习示例

在本节中,我们将让你尝试处理一些字符串操作代码。 在下面的每个练习中,我们有一个字符串数组和一个循环,处理数组中的每个值,并将其显示在项目符号列表中。 你现在不需要理解数组或循环 - 这些将在以后的文章中解释。 在每种情况下,你需要做的是编写将以我们想要的格式输出字符串的代码。

每个示例都有一个重置按钮,您可以使用它来重置代码,如果你犯了一个错误,无法让它再次工作,并显示解决方案按钮你 可以按看到一个潜在的答案,如果你真的卡住了。

过滤问候消息

在第一个练习中,我们将从简单的开始 - 我们有一个贺卡消息的数组,但我们要排序他们只列出圣诞节消息。 我们希望您在 if(...)结构中填写一个条件测试,以测试每个字符串,并且只在圣诞节消息中将其打印在列表中。

  1. First think about how you could test whether the message in each case is a Christmas message. What string is present in all of those messages, and what method could you use to test whether it is present?
  2. You'll then need to write a conditional test of the form operand1 operator operand2. Is the thing on the left equal to the thing on the right? Or in this case, does the method call on the left return the result on the right?
  3. Hint: In this case it is probably more useful to test whether the method call isn't equal to a certain result.

固定大写

在这个练习中,我们有英国城市的名字,但资本化都被搞砸了。 我们希望您更改它们,使它们都是小写字母,除了首字母大写。 一个很好的方法是:

  1. Convert the whole of the string contained in the input variable to lower case and store it in a new variable.
  2. Grab the first letter of the string in this new variable and store it in another variable.
  3. Using this latest variable as a substring, replace the first letter of the lowercase string with the first letter of the lowercase string changed to upper case. Store the result of this replace procedure in another new variable.
  4. Change the value of the result variable to equal to the final result, not the input.

注意:提示 - 字符串方法的参数不必是字符串字面量; 它们也可以是变量,或者甚至是在其上调用方法的变量。

从旧零件创建新字符串

在最后一个练习中,数组包含一串字符串,包含关于英格兰北部火车站的信息。 字符串是包含三个字母站代码的数据项,后面是一些机器可读数据,后面是分号,后面是人工可读的站名。 例如:

MAN675847583748sjt567654;Manchester Piccadilly

我们要提取站的代码和名称,并将它们放在一个字符串中,具有以下结构:

MAN: Manchester Piccadilly

我们要提取站的代码和名称,并将它们放在一个字符串中,具有以下结构:...

  1. Extract the three-letter station code and store it in a new variable.
  2. Find the character index number of the semi-colon.
  3. Extract the human-readable station name using the semi-colon character index number as a reference point, and store it in a new variable.
  4. Concatenate the two new variables and a string literal to make the final string.
  5. Change the value of the result variable to equal to the final string, not the input.

结论

我们建议这样做:...

Handling text — strings in JavaScript
Server-side web frameworks
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录
CSS

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }