日期:2014-05-16 浏览次数:20322 次
五.Strings and Regular Expressions
?? Practically all JavaScript programs are intimately tied to strings. For example, many applications use Ajax to fetch strings from a server, convert those strings into more easily usable JavaScript objects, and then generate strings of HTML from the data. A typical program deals with numerous tasks like these that require you to merge, split, rearrange, search, iterate over, and otherwise handle strings; and as web applications become more complex, progressively more of this processing is done in the browser.
? ?In JavaScript, regular expressions are essential for anything more than trivial string processing. A lot of this chapter is therefore dedicated to helping you understand how regular expression engines internally process your strings and teaching you how to write regular expressions that take advantage of this knowledge. ?Also in this chapter, you’ll learn about the fastest cross-browser methods for concatenating and trimming strings, discover how to increase regex performance by reducing backtracking, and pick up plenty of other tips and tricks for efficiently processing strings and regular expressions.
Method | Example |
The + operator | str = "a" + "b" + "c"; |
The += operator |
str = "a"; str += "b"; str += "c";? |
array.join() | str = ["a", "b", "c"].join(""); |
string.concat() |
tr = "a";? str = str.concat("b", "c"); |
str += "one" + "two";?When evaluating this code, four steps are taken:
str += "one"; str += "two";?? In fact, you can get the same performance improvement using one statement, as follows:
str = str + "one" + "two"; // equivalent to str = ((str + "one") + "two")??? This avoids the temporary string because the assignment expression starts with str as the base and appends one string to it at a time, with each intermediary concatenation performed from left to right. If the concatenation were performed in a different order (e.g., str = "o