String manipulation in JavaScript

Source: Internet
Author: User
Tags object character set contains count empty expression variables sort
Javascript| string

I. Overview
Strings are almost ubiquitous in JavaScript, and when you're dealing with user input data, when you're reading or setting the properties of a DOM object, there's certainly more to it when you're manipulating cookies .... The core part of JavaScript provides a set of properties and methods for common string operations, 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, the main is to introduce some of the operation of the string itself, regular expressions will be in future essays involved.

Second, the creation of strings
There are several ways to create a string. The simplest is to enclose a set of characters in quotation marks and assign them to a string variable.
var mystr = "Hello, string!";
You can enclose a string in double or single quotes, but note that a pair of quotes as a defined string must be the same and cannot be mixed.
like var myString = "Fluffy is a pretty cat." Such a statement is illegal.
Allowing the use of two quotes makes some operations simple, such as embedding one into another:
document.write ("

    we created a few strings in the script above, but in essence they are not real string objects, they are, to be exact, values of string types. To create a string object, you can use the following statement: var strobj = new String ("Hello, string!");
    Use the typeof operator to see that the above mystr type is string and the Strobj type is object.
   
    use its Length property if you want to know the length of the string: String.Length.
    Gets the character used at the specified position of the string: String.charat (index);

third, string concatenation
question:
    stitch two or more strings together into a large string
Solution:
     Very simple, "add" two strings with a "+":
    var longstring = "One Piece" + "plus one more piece.";
    to accumulate more than one string as a string, you can also use the "+ =" operator:
    var result = "";
    result = ' My name is Anders '
    result = ' and my ' age ';  
&nbs p;  
    To add line breaks in a string, you need to use the escape character "\ n":
    var confirmstring = "You did not Enter a response to the last "+
       " question.\n\nsubmit form anyway? ";
    var confirmvalue = confirm (confirmstring);
    But this method can only be used in situations like a warning, confirmation dialog box, and if you render the text as HTML content, it is not valid, and then replace it with "<br>":
     var htmlstring = "A. String.<br>second line of String.";
    document.write (htmlstring);

The string object also provides a method concat () that completes the same function as "+":
String.Concat (value1, value2, ...)
But Concat () method is obviously not as "+" come intuitive simplicity.

Iv. accessing substrings of strings
Problem:
Gets a copy of a part of a string.
Solution:
Using the substring () or slice () method (nn4+, ie4+), the specific use of them is described below.
The prototype of substring () is: string.substring (from, to)
The first argument from specifies the starting position of the substring in the original string (based on the 0 index); the second argument to is optional, which specifies the substring at the end of the original string (based on the 0 index), and generally, it should be larger than from, if it is omitted, The substring is then kept at the end of the original string.
What happens if the parameter from is accidentally larger than the parameter? JavaScript automatically mediates the start and end of a substring, which means that substring () always starts with the smaller of the two arguments, and ends with the larger one. Note, however, that it contains that character from the starting position, but does not contain the character at the end position.
var fullstring = "Every dog has his day."
var section = fullstring.substring (0, 4); The section is "Ever".
Section = fullstring.substring (4, 0); The section is also "Ever".
Section = fullstring.substring (1, 1); The section is a 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 indicates the starting position of the substring and, if it is a negative number, it can be understood as the beginning of the penultimate, for example, 3, starting at the last third, and the argument end representing the ending position, which, like start, can also be negative, and its meaning to the penultimate end. The slice () parameter can be negative, so it is more flexible than substring (), but less forgiving, and if start is larger than end, it returns an empty string (example).
Another method is substr (), whose prototype is: String.substr (start, length)
From the prototype, you can see the meaning of its arguments, start represents the starting position, and length represents the substring. JavaScript standards do not encourage the use of this method.
V. Case conversion of strings
Problem:
There is a text box on your page that receives input from the user, such as cities, then you will do different processing according to his city's different, at this time will use the string comparison naturally, then, before comparing, it is best to do the case conversion, so as long as the conversion of the situation can be considered, or to collect data on the page, The data is then stored in the database, and the database just receives uppercase characters, and in these cases we consider the case conversion of the string.
Solution:
Use the toLowerCase () and toUpperCase () methods:
var city = "Shanghai";
City = City.tolowercase (); The city is the "Shanghai" now.
Six, to determine whether two strings are equal
Problem:
For example, you want to compare the user's input value with a known string
Solution:
First convert the user's input value to uppercase (or lowercase), and then compare:
var name = Document.form1.txtUserName.value.toLowerCase ();
if (name = = "Urname")
{
Statements go.
}
JavaScript has two kinds of equality operators. One is completely backwards compatible, the standard "= =", if two operand types are inconsistent, it will automatically type the operand at some time, consider 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 string, the latter is object, and when you use the "= =" operator, JavaScript tries various values to detect whether the two are equal in some case. So the following expression results in True:stra = = Strb.
The second operator is "strict" "= = =", it will not be so tolerant when the evaluation, will not be type conversion. So the value of the expression stra = = = Strb is False, although both variables hold the same value.
Sometimes the logic of the code requires you to determine whether two values are not equal, there are also two choices: "!=" and Strict "!==", their relationship is similar to "= =" and "= =".
Discuss:
"= =" and "!=" look for the matching of values as much as possible, but you might want to make explicit type conversions before you compare them to "help" them get the job done. For example, if you want to determine whether a user's input value (a string) equals a number, you can let "= =" help you complete the type conversion:
if (Document.form1.txtAge.value = = Somenumericvar) {...}
You can also convert in advance:
if (parseint (document.form1.txtAge.value) = = Somenumericvar) {...}
If you are more accustomed to strongly typed programming languages (such as C#,java, etc.), you can extend your habits (type conversions) here, which will also enhance the readability of the program.

One thing to note is the locale of the computer. If you use "<" and ">" to compare strings, JavaScript compares them as Unicode, but it is clear that people do not read text as Unicode when browsing the Web: In Spanish, for example, in traditional order, "ch" will be ranked as a character between "C" and "D". Localecompare () provides a way to help you use character collation under the default locale.
var strings; An array of strings to sort, assuming that they have been initialized
Strings.sort (function (a,b) {return a.localecompare (b)}); Call the sort () method to sort

Seven, the search for strings
Problem:
Determines whether a string contains another string.
Solution:
Use String's IndexOf () method:
Strobj.indexof (substring[, StartIndex])
Strobj is the string to be judged, substring is the substring to find in Strobj, startindex is optional, represents the starting position of the lookup (based on a 0 index), and if the startindex is omitted, it is found from the beginning of the strobj. If the startindex is less than 0, start at 0, and if startindex is greater than the maximum index, start at the maximum index.
IndexOf () returns the starting position of substring in strobj, or 1 if it is not found. In the script, you can use this:
if (Largestring.indexof (shortstring)!=-1)
{
If it is included, handle it accordingly;
}
Maybe a string will contain another string more than once, when the second argument startindex might come in handy, and the following function shows how to get the number of times a string contains another string:
function Countinstances (MAINSTR, SUBSTR)
{
var count = 0;
var offset = 0;
Todo
{
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 the indexof (), LastIndexOf ():
Strobj.lastindexof (substring[, startindex])
Strobj is the string to be judged, substring is the substring to find in Strobj, startindex is optional, represents the starting position of the lookup (based on a 0 index), and if the startindex is omitted, the end of the strobj is found. If the startindex is less than 0, start at 0, and 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 strobj, and returns-1 if it is not found.

Converting between characters in Unicode values and strings
Problem:
Gets the Unicode encoding value of one character, and vice versa.
Solution:
To get Unicode encoding for a character, 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 (based on a 0 index), and returns a 16-bit integer value between 0 and 65535. For example:
var strobj = "ABCDEFG";
var code = strobj.charcodeat (2); Unicode value of character ' C ' is 67
The return value is Nan if there are no characters at the index specified by index.

To convert a Unicode encoding to a character, use the String.fromCharCode () method to note that it is a "static method" of a string object, meaning that you do not need to create a string instance before you use it:
String.fromCharCode (c1, c2, ...)
It accepts 0 or more integers and returns a string that contains the characters specified by each parameter, for example:
var str = String.fromCharCode (72, 101, 108, 108, 111); str = "Hello"
Discuss:
Unicode contains the character sets for many of the world's writing languages, but don't expect this character to be displayed properly when a warning dialog box, text box, or page renders, because Unicode contains a single character. If the character set is not available, the page will appear as a question mark or other symbol. A typical North American computer will not be able to display Chinese characters on the screen unless the character set and its fonts are installed.

Reference:
JavaScript and Dhtml Cookbook (oreilly);
Javascript-the Definitive Guide (4th Edition);



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.