codecamp

Handling text — strings in JavaScript

先决条件: 基本的计算机素养,基本了解HTML和CSS,了解JavaScript是什么。
目的: 熟悉JavaScript中字符串的基础知识。

词语的力量

言语对人类非常重要 - 它们是我们如何沟通的很大一部分。 由于Web是一种基本上是基于文本的媒体,旨在允许人们进行交流和共享信息,因此我们有必要控制出现在其上的词语。 "> HTML 为我们的文本提供结构和含义, CSS(层叠样式表)是一种声明性语言,用于控制浏览器中网页的外观。"> CSS 允许我们精确地设置样式,JavaScript包含了一些操作字符串的功能,创建自定义的欢迎消息, 在需要时,右边的文本标签,排序术语到所需的顺序,这么多。

几乎所有我们向你展示的程序都涉及到一些字符串操作。

字符串 - 基础

字符串以类似于数字的方式处理,乍一看,但你会开始看到一些显着的差异,当你深入。 让我们开始在控制台中输入一些基本线条来熟悉自己。 我们在下面提供了一个(您也可以 >在单独的标签或窗口中打开此控制台,或者如果愿意,可以使用浏览器开发者控制台)。

创建字符串

  1. To start with, enter the following lines:
    var string = 'The revolution will not be televised.';
    string;
    Just like we did with numbers, we are declaring a variable, initializing it with a string value, and then returning the value. The only difference here is that when writing a string, you need to surround the value with quotes.
  2. If you don't do this, or miss one of the quotes, you'll get an error. Try entering the following lines:
    var badString = This is a test;
    var badString = 'This is a test;
    var badString = This is a test';
    These lines don't work because any text string without quotes around it is assumed to be a variable name, property name, reserved word, or similar. If the browser can't find it, then an error is raised (e.g. "missing ; before statement"). If the browser can see where a string starts, but can't find the end of the string, as indicated by the 2nd quote, it complains with an error (with "unterminated string literal"). If your program is raising such errors, then go back and check all your strings to make sure you have no missing quote marks.
  3. The following will work if you previously defined the variable string — try it now:
    var badString = string;
    badString;
    badString is now set to have the same value as string.

单引号和双引号

  1. In JavaScript, you can choose single quotes or double quotes to wrap your strings in. Both of the following will work OK:
    var sgl = 'Single quotes.'
    var dbl = "Double quotes";
    sgl;
    dbl;
  2. There is very little difference between the two, and which you use is down to personal preference. You should choose one and stick to it, however, differently quoted code can be confusing, especially if you use the different quotes on the same string! The following will return an error:
    var badQuotes = 'What on earth?";
  3. The browser will think the string has not been closed, because the other type of quote you are not using to contain your strings can appear in the string. For example, both of these are OK:
    var sglDbl = 'Would you eat a "fish supper"?'
    var dblSgl = "I'm feeling blue.";
    sglDbl;
    dblSgl;
  4. However, you can't include the same quote mark inside the string as is being used to contain them. The following will error, as it confuses the browser as to where the string ends:
    var bigmouth = 'I've got no right to take my place...';
    This leads us very nicely onto our next subject.

转义字符串中的字符

要修复我们以前的问题代码行,我们需要转义问题引号。 转义字符意味着我们对它们做一些事情,以确保它们被识别为文本,而不是代码的一部分。 在JavaScript中,我们通过在字符之前放置一个反斜杠来实现。 尝试这个:

var bigmouth = 'I\'ve got no right to take my place...';
bigmouth;

这工作正常。 您可以使用相同的方式转义其他字符,例如 \\",另外还有一些特殊的代码,请参阅 Escape_notation"> Escape notation 了解更多详情。

连接字符串

  1. Concatenate is a fancy programming word that means "join together". Joining together strings in JavaScript uses the plus (+) operator, the same one we use to add numbers together, but In this context it does something different. Let's try an example in our console.
    var one = 'Hello, ';
    var two = 'how are you?';
    var joined = one + two;
    joined;
    The result of this is a variable called joined, which contains the value "Hello, how are you?".
  2. In the last instance, we just joined two strings together, but you can do as many as you like, as long as you include a + between each one. Try this:
    var multiple = one + one + one + one + two;
    multiple;
  3. You can also use a mix of variables and actual strings. Try this:
    var response = one + 'I am fine — ' + two;
    response;

注意:当您在代码中输入包含单引号或双引号的实际字符串时,会将其称为字符串文字

上下文中的连接

让我们来看看在行动中使用的连接 - 这是本课程早期的一个例子:

<button>Press me</button>
var button = document.querySelector('button');

button.onclick = function() {
  var name = prompt('What is your name?');
  alert('Hello ' + name + ', nice to see you!');
}

这里我们使用 消息提示用户输入一些文本"> Window.prompt() 函数在第4行,它要求用户通过弹出对话框回答一个问题,然后存储文本 输入给定变量(在本例中为 name )。 然后,我们使用 指定内容和OK按钮"> Window.alert() 函数在第5行显示另一个弹出框,其中包含我们从两个字符串文字和名称 变量,通过连接。

数字与字符串

  1. So what happens when we try to add (or concatenate) a string and a number? Let's try it in our console:
    'Front ' + 242;
    
    You might expect this to throw an error,  but it works just fine. Trying to represent a string as a number doesn't really make sense, but representing a number as  a string does, so the browser rather cleverly converts the number to a string and concatenates the two strings together.
  2. You can even do this with two numbers — you can force a number to become a string by wrapping it in quote marks. Try the following (we are using the typeof operator to check whether the variable is a number or a string):
    var myDate = '19' + '67';
    typeof myDate;
  3. If you have a numeric variable that you want to convert to a string but not change otherwise, or a string variable that you want to convert to a number but not change otherwise, you can use the following two constructs:
    • The Number object will convert anything passed to it into a number, if it can. Try the following:
      var myString = '123';
      var myNum = Number(myString);
      typeof myNum;
    • On the other hand, every number has a method called toString() that will convert it to the equivalent string. Try this:
      var myNum = 123;
      var myString = myNum.toString();
      typeof myString;
    These constructs can be really useful in some situations, for example if a user enters a number into a form text field it will be a string, but if you want to add it to something say, you'll need it to be a number, so you could pass it through Number() to handle this. We did exactly this in our Number Guessing Game, in line 63.

结论

这是JavaScript中的字符串的基础。 在下一篇文章中,我们将基于这一点,查看一些可用于JavaScript中的字符串的内置方法,以及我们如何使用它们来将我们的字符串操作为我们想要的形式。

Basic math in JavaScript — numbers and operators
Useful string methods
温馨提示
下载编程狮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; }