In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "what is the javascript string operation method". In the daily operation, I believe that many people have doubts about what the javascript string operation method is. The editor consulted all kinds of data and sorted out a simple and easy-to-use operation method. I hope it will be helpful for you to answer the question of "what is the javascript string operation method?" Next, please follow the editor to study!
I. Overview
Strings are almost ubiquitous in JavaScript, and there are certainly more when you are dealing with user input data, when reading or setting properties of DOM objects, and when manipulating cookie. The core of JavaScript provides a set of properties and methods for general string manipulation, such as splitting strings, changing the case of strings, manipulating substrings, and so on.
Most current browsers can also benefit from powerful regular expressions because it greatly simplifies a lot of string manipulation tasks, but it also requires you to overcome a somewhat steep learning curve. Here, I mainly introduce some operations of the string itself, and regular expressions will be covered in later essays.
Second, the creation of strings
There are several ways to create a string. The simplest thing is to enclose a set of characters in quotation marks, which can be assigned to a string variable.
Var myStr = "Hello, String!"
You can enclose a string in double or single quotation marks, but note that a pair of quotation marks that define a string must be the same and cannot be mixed.
Claims like var myString = "Fluffy is a pretty cat.'; are illegal.
Two quotation marks are allowed to make some operations simple, such as embedding one into the other:
[xss_clean] (")
We created several strings in the above script, but in essence, they are not really string objects, to be exact, they are string type values. To create a string object, use the following statement: var strObj = new String ("Hello, String!")
Using the typeof operator, you can see that the above myStr type is string, while the strObj type is object.
If you want to know the length of a string, use its length attribute: string.length.
The character usage method to get the specified position of the string: string.charAt (index)
III. Concatenation of strings
Question:
Concatenate two or more strings into one large string
Solution:
It's very simple to "add" two strings with a "+":
Var longString = "One piece" + "plus one more piece."
To accumulate multiple strings into one string, you can also use the "+ =" operator:
Var result = ""
Result + = "My name is Anders"
Result + = "and my age is 25"
To add newline characters to a string, you need to use the escape character "":
Var confirmString = "You did not enter a response to the last" +
Question. Submit form anyway?
Var confirmValue = confirm (confirmString)
However, this method can only be used in situations such as warnings and confirmation dialogs. If the text is rendered as HTML content, it will be invalid. Use "
"replace it:
Var htmlString = "First line of string.
Second line of string. "
[xss_clean] (htmlString)
The String object also provides the method concat (), which performs the same function as "+":
String.concat (value1, value2,...)
However, the concat () method is obviously not as intuitive and concise as the "+" method.
4. Access the substring of a string
Question:
Get a copy of part of a string.
Solution:
Using the substring () or slice () method (NN4+, IE4+), the specific usage of these methods is described below.
The prototype of substring () is: string.substring (from, to)
The first parameter from specifies the starting position of the substring in the original string (based on the index of 0); the second parameter to is optional, it specifies the position of the substring at the end of the original string (the index based on 0), in general, it should be larger than from, if it is omitted, then the substring will go all the way to the end of the original string.
What if the parameter from is accidentally larger than the parameter to? JavaScript automatically mediates the start and end position of the substring, that is, substring () always starts with the smaller of the two parameters and ends with the larger one. Note, however, that it contains the character of the starting position, but not the character of the end position.
Var fullString = "Every dog has his day."
Var section = fullString.substring (0,4); / / section is "Ever".
Section = fullString.substring (4,0); / / section is also "Ever".
Section = fullString.substring (1,1); / / section is an empty string.
Section = fullString.substring (- 2,4); / / section is "Ever", same as fullString.substring (0,4); the prototype of slice () is: string.slice (start, end)
The parameter start represents the starting position of the substring. If it is negative, it can be understood as the beginning of the penultimate. For example,-3 means starting from the penultimate; the parameter end represents the end position. Like start, it can also be negative, and it also means the end of the penultimate. The argument to slice () can be negative, so it's more flexible than substring (), but less forgiving, and if start is larger than end, it returns an empty string (the example is slightly scanned).
Another method is substr (), whose prototype is string.substr (start, length).
You can see the meaning of its parameters from the prototype, with start indicating the starting position and length indicating the length of the substring. This method is not recommended by the JavaScript standard.
5. Case conversion of strings
Question:
There is a text box on your page to receive user input information, such as cities, and then you will do different processing according to his city, and string comparison will be used naturally, so it is best to convert case before comparison, so as long as you consider the situation after conversion; or you need to collect data on the page and store it in the database, which happens to receive only uppercase characters. In these cases, we should consider case conversion of strings.
Solution:
Use the toLowerCase () and toUpperCase () methods:
Var city = "ShanGHai"
City = city.toLowerCase (); / / city is "shanghai" now.
6. Judge whether two strings are equal
Question:
For example, you want to compare the user's input value with a known string
Solution:
Convert all user input values to uppercase (or lowercase) first, and then compare:
Var name = document.form1.txtUserName.value.toLowerCase ()
If (name = = "urname")
{
/ / statements go here.
}
JavaScript has two equality operators. One is fully backward compatible, the standard "= =". If the two operands are inconsistent, it will automatically convert the operands at some point, considering the following assignment statement:
Var strA = "i love you!"
Var strB = new String ("i love you!")
The two variables contain the same sequence of characters, but the data types are different, the former is string and the latter is object, and when using the "= =" operator, JavaScript tries various evaluations to see if the two are equal under certain circumstances. So the following expression results in true: strA = = strB.
Pay special attention to whether the type of two strings is the same when judging that two strings are equal.
The second operator is the "strict"=", which is not so tolerant in evaluation and does not cast types. So the value of the expression strA = = strB is false, although the two variables hold the same value.
Sometimes the logic of the code requires you to determine whether two values are not equal, and there are two options: "! =" and strict "! =", and their relationship is similar to "=" and "=".
Discussion:
"=" and "!" will look for the matching of values as much as possible when evaluating, but you may still want to do explicit type conversions before comparison to "help" them get the job done. For example, if you want to determine whether a user's input value (string) is equal to a number, you can let "=" help you with the type conversion:
If (document.form1.txtAge.value = = someNumericVar) {...}
You can also switch ahead of time:
If (parseInt (document.form1.txtAge.value) = = someNumericVar) {.}
If you are more accustomed to strongly typed programming languages (such as Category Java, etc.), then you can continue your habit here (type conversion), which will also enhance the readability of the program.
One situation to be aware of is the locale of the computer. If you compare strings with "", JavaScript compares them as Unicode, but obviously people don't read text as Unicode when browsing the web:) in Spanish, for example, "ch" is arranged as a character between "c" and "d" in traditional order. LocaleCompare () provides a way to help you use the character collation under the default locale.
Var strings; / / an array of strings to be sorted, assuming it has been initialized
Strings.sort (function (a) b) {return a.localeCompare (b)}); / / call the sort () method to sort
Seventh, the search of strings
Question:
Determines whether one string contains another string.
Solution:
Use the indexOf () method of string:
StrObj.indexOf (subString [, startIndex])
StrObj is the string to be judged, subString is the substring to be found in strObj, startIndex is optional, indicating the start position of the search (index based on 0), if startIndex is omitted, then start at strObj, if startIndex is less than 0, start at 0, if startIndex is greater than the maximum index, start at the maximum index.
IndexOf () returns the start position of the subString in the strObj, or-1 if it is not found. In a script, you can use:
If (largeString.indexOf (shortString)! =-1)
{
/ / if included, deal with it accordingly
}
Maybe a string will contain another string more than once, and the second parameter startIndex may come in handy. The following function demonstrates how to find the number of times a string contains another string:
Function countInstances (mainStr, subStr)
{
Var count = 0
Var offset = 0
Do
{
Offset = mainStr.indexOf (subStr, offset)
If (offset! =-1)
{
Count++
Offset + = subStr.length
}
While (offset! =-1)
Return count
}
The String object has a method corresponding to indexOf (), lastIndexOf ():
StrObj.lastIndexOf (substring [, startindex])
StrObj is the string to be judged, subString is the substring to be looked up in strObj, startIndex is optional, indicating the start of the search (index based on 0), if startIndex is omitted, search at the end of strObj, if startIndex is less than 0, start at 0, if startIndex is greater than the maximum index, start at the maximum index. This method looks from right to left, returns the last occurrence of subString in the strObj, and returns-1 if it is not found.
Conversion between Unicode values and characters in strings
Question:
Gets the Unicode-coded value of a character, and vice versa.
Solution:
To obtain the Unicode encoding of characters, you can use the string.charCodeAt (index) method, which is defined as:
StrObj.charCodeAt (index)
Index is the position of the specified character in the strObj object (an index based on 0), and the return value is a 16-bit integer between 0 and 65535. For example:
Var strObj = "ABCDEFG"
Var code = strObj.charCodeAt (2); / / Unicode value of character 'C'is 67
If there are no characters at the index specified by index, the return value is NaN.
To convert Unicode encoding to a character, use the String.fromCharCode () method, which is a "static method" of the String object, meaning that you do not need to create a string instance before using it:
String.fromCharCode (C1, c2,...)
It accepts 0 or more integers and returns a string containing the characters specified by each parameter, for example:
Var str = String.fromCharCode (72,101,108,108,111); / / str = = "Hello"
[@ more@]
/ * *
1. Trim string
, /
Function LTrim (str)
{
Var whitespace = new String ("")
Var s = new String (str)
If (whitespace.indexOf (s.charAt (0))! =-1)
{
Var jung0, I = s.length
While (j)
< i && whitespace.indexOf(s.charAt(j)) != -1) { j++; } s = s.substring(j, i); } return s; } function RTrim(str) { var whitespace = new String(" "); var s = new String(str); if (whitespace.indexOf(s.charAt(s.length-1)) != -1) { var i = s.length - 1; while (i >= 0 & whitespace.indexOf (s.charAt (I))! =-1)
{
IMurray-
}
S = s.substring (0, iTun1)
}
Return s
}
Function Trim (str)
{
Return RTrim (LTrim (str))
}
/ * 2. Email validator*/
Function checkMail (email) {
Email = Trim (email)
Var rep = / ^ w + ([- +.] w +) * @ w + ([-.] w +) * .w + ([-.] w +) * $/
/ / alert (rep.test (email))
If (email = = "" | | email.length
< 5 || email.length>50) {
Return false
} else if (rep.test (email)) {
Return true
} else {
Return false
}
}
At this point, the study on "what is the method of manipulating javascript strings" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.