Handling text — strings in JavaScript

2018-05-15 17:26 更新
先決條件: 基本的計算機素養(yǎng),基本了解HTML和CSS,了解JavaScript是什么。
目的: 熟悉JavaScript中字符串的基礎(chǔ)知識。

詞語的力量

言語對人類非常重要 - 它們是我們?nèi)绾螠贤ǖ暮艽笠徊糠帧?/span> 由于Web是一種基本上是基于文本的媒體,旨在允許人們進行交流和共享信息,因此我們有必要控制出現(xiàn)在其上的詞語。 "> HTML 為我們的文本提供結(jié)構(gòu)和含義, CSS(層疊樣式表)是一種聲明性語言,用于控制瀏覽器中網(wǎng)頁的外觀。"> CSS 允許我們精確地設(shè)置樣式,JavaScript包含了一些操作字符串的功能,創(chuàng)建自定義的歡迎消息, 在需要時,右邊的文本標簽,排序術(shù)語到所需的順序,這么多。

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

字符串 - 基礎(chǔ)

字符串以類似于數(shù)字的方式處理,乍一看,但你會開始看到一些顯著的差異,當你深入。 讓我們開始在控制臺中輸入一些基本線條來熟悉自己。 我們在下面提供了一個(您也可以 >在單獨的標簽或窗口中打開此控制臺,或者如果愿意,可以使用瀏覽器開發(fā)者控制臺)。

創(chuàng)建字符串

  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.

轉(zhuǎn)義字符串中的字符

要修復我們以前的問題代碼行,我們需要轉(zhuǎn)義問題引號。 轉(zhuǎn)義字符意味著我們對它們做一些事情,以確保它們被識別為文本,而不是代碼的一部分。 在JavaScript中,我們通過在字符之前放置一個反斜杠來實現(xiàn)。 嘗試這個:

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

這工作正常。 您可以使用相同的方式轉(zhuǎn)義其他字符,例如 \\",另外還有一些特殊的代碼,請參閱 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() 函數(shù)在第4行,它要求用戶通過彈出對話框回答一個問題,然后存儲文本 輸入給定變量(在本例中為 name )。 然后,我們使用 指定內(nèi)容和OK按鈕"> Window.alert() 函數(shù)在第5行顯示另一個彈出框,其中包含我們從兩個字符串文字和名稱 變量,通過連接。

數(shù)字與字符串

  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.

結(jié)論

這是JavaScript中的字符串的基礎(chǔ)。 在下一篇文章中,我們將基于這一點,查看一些可用于JavaScript中的字符串的內(nèi)置方法,以及我們?nèi)绾问褂盟鼈儊韺⑽覀兊淖址僮鳛槲覀兿胍男问健?/span>

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號