String manipulation in JavaScript

  • 2020-03-29 23:41:46
  • OfStack

An overview,
      Strings are ubiquitous in JavaScript, when you're dealing with user input data, when you're reading or setting properties on DOM objects, when you're manipulating cookies, and more. . The core 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 browsers today also benefit from powerful regular expressions because they greatly simplify a large number of string manipulation tasks, but they also require you to overcome a somewhat steep learning curve. Here, I'll focus on some of the operations of the string itself, which regular expressions will cover in a future post.

Two, string creation
      There are several ways to create a string. The simplest is to enclose a set of characters in quotation marks, which you can assign to a string variable.
      Var myStr = "Hello, String!" ;
      You can include a string in double or single quotes, but note that the pair of quotes that define the string must be the same and cannot be mixed.
      Var myString = "Fluffy is a pretty cat. "; Such a statement is illegal.
      Two kinds of quotes are allowed, making it easy to do things like embed one in the other:

document.write("<img src='img/logo.jpg' height='30' width='100' alt='Logo'>");

      We created several strings in the script above, but essentially they are not really string objects, they are exactly string-type values. To create a String object, use the following statement: var strObj = new String("Hello, String!") );
      A look using the typeof operator shows that the type myStr above is string and the type strObj is object.

      If you want to know the length of a string, use its length property: string.length.
      String. CharAt (index);

Third, string concatenation
      Concatenate two or more strings into one large string
      Simply add the two strings with a "+" :

var longString = "One piece " + "plus one more piece."; 

      To accumulate multiple strings into a single string, you can also use the "+=" operator:

var result = "";
result += "My name is Anders"
result += " and my age is 25";   

      To add a newline character to a string, use the escape character "\n" :

var confirmString = "You did not enter a response to the last " +
        "question.nnSubmit form anyway?";
var confirmValue = confirm(confirmString);

      However, this method can only be used in situations such as warning and confirmation dialogs. If the text is rendered as HTML content, it is not valid. Br>" Instead of it:

var htmlString = "First line of string.<br>Second line of string.";

      The String object also provides the method concat(), which does the same thing as "+" :
      String concat (value1, value2,...).
      Concat (), however, is not as intuitive and simple as "+".

A substring of an access string
      Gets a copy of part of a string.
      Use the substring() or slice() methods (NN4+, IE4+), with the following instructions.
      The prototype for substring() is:   String. The substring (the from and to)
      The first parameter, from, specifies the starting position of the substring in the original string (a zero-based index). The second argument, to, is optional and specifies the substring at the end of the original string (a zero-based index), which should be larger than from in general, and if it is omitted, the substring will go all the way to the end of the original string.
      What happens if the argument from is accidentally larger than the argument to? JavaScript automatically mediates the starting and ending position of the substring, that is, the substring() always starts with the smaller of the two arguments and ends with the larger one. Note, however, that it contains the character at the beginning, but not the character at the end.

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: & PI; String. Slice (start, end)
      The parameter start represents the starting position of the substring. If it is negative, it can be understood as the reciprocal starting point. For example, -3 means starting from the third from the bottom. The parameter "end" indicates the end position. Like "start", it can also be negative, and its meaning also indicates the end to the reciprocal. Slice () can have a negative argument, so it's more flexible than substring(), but less forgiving; if start is larger than end, it returns an empty string(omitted in the example).
      Another method is substr(), whose prototype is: string.substr(start, length)
      You can see from the prototype what its parameters mean, start for the starting position and length for the length of the substring. The JavaScript standard does not advocate this approach.
Five, string case conversion
      On your page, there is a text box to receive the user's input information, such as the city, and then you will do different processing according to his city, then the natural use of string comparison, so before the comparison, the best case conversion, so as long as you consider the conversion can; Or collect data on a page and store it in a database that happens to receive only uppercase characters. In all of these cases, we want to consider case - case conversion of strings.
      Using the toLowerCase() and toUpperCase() methods:

var city = "ShanGHai";
city = city.toLowerCase();  // city is "shanghai" now.

Determine if two strings are equal
      For example, you want to compare the user's input value to a known string
      First, convert all the input values of the user to uppercase (or lowercase), and then make a comparison:

var name = document.form1.txtUserName.value.toLowerCase();
    if(name == "urname")
        // statements go here.

      JavaScript has two kinds of equality operators. One is fully backward compatible, the standard "==", which automatically casts operands at some point if the two operands are of different types. 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 have different data types. The former is string and the latter is object. When using the "==" operator, JavaScript tries various evaluations to see if the two will be equal in some case. So the following expression is true: strA == strB.
      The second operator, the "strict" "===" operator, is not so forgiving in its evaluation and does not cast. So the expression strA === strB has a value of false, even though the two variables hold the same value.
      Sometimes the logic of the code requires you to determine if two values are different, and there are two choices: "! =" and strict "! ==", their relationship is similar to "==" and "===".
      "= =" and "! =" when evaluating values, try to find as many matches as possible, but you may want to cast them explicitly 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 use "==" to do the type conversion:
      If (document. Form1. TxtAge. Value = = someNumericVar) {... }
      Can also be converted in advance:
      If (parseInt (value). The document form1. TxtAge. = = someNumericVar) {... }
      If you are used to strongly typed programming languages (such as C#,Java, etc.), then here you can continue your habit (type conversion), which will also enhance the readability of the program.

      One thing to note is the locale of the computer. If use "<" And ">" To compare strings, JavaScript compares them as Unicode, but obviously, people don't read text as Unicode when browsing the web :) in Spanish, for example, "ch" would be placed as a character between "c" and "d" in the traditional order. LocaleCompare () provides a way for you to use the character collation under the default locale.

var strings;  //The array of strings to sort, assuming it has been initialized
strings.sort(function(a,b) { return a.localeCompare(b) });  //Call the sort() method to sort

Seven, string search
      Determines whether a string contains another string.
      IndexOf () method of string:
      StrObj. IndexOf (subString [startIndex])
      StrObj is the string to be judged and subString is the subString to be searched in strObj. StartIndex is optional, indicating the starting position of the search (index based on 0). If startIndex is omitted, the search starts from strObj.
      IndexOf () returns the starting position of the subString in strObj, or -1 if it is not found. In the script, you can use:

if(largeString.indexOf(shortString) != -1)
        //If so, handle accordingly;

      Perhaps a string will contain another string more than once, in which case the second parameter startIndex may come in handy. This function demonstrates how to find the number of times a string contains another string:

   function countInstances(mainStr, subStr)
        var count = 0;
        var offset = 0;
            offset = mainStr.indexOf(subStr, offset);
            if(offset != -1)
                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 and subString is the subString to be searched in strObj. StartIndex is optional, indicating the starting position of the search (index based on 0). If startIndex is omitted, it is searched from the end of strObj. This method looks from right to left and returns the last location of the subString in strObj, or -1 if it is not found.

Convert between Unicode values and characters in strings
      Gets the Unicode encoding value for a character and vice versa.
      To obtain the Unicode encoding of a character, 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 (a 0 based index) and returns a 16-bit integer between 0 and 65535. Such as:

      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 the Unicode encoding to a character, use the string.fromcharcode () method, noting that it 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 and c2,...).
      It accepts 0 or more integers and returns a string containing the characters specified for each argument, such as:

var str = String.fromCharCode(72, 101, 108, 108, 111);  // str == "Hello"

        Unicode contains the character set of many of the world's written languages, but just because Unicode contains a character does not mean that it is expected to display properly in warning dialogs, text boxes, or page renders. If the character set is not available, it will appear as a question mark or other symbol on the page. A typical north American computer will not be able to display Chinese characters on the screen unless the Chinese character set and its fonts have been installed.

      JavaScript And Dhtml Cookbook (Oreilly)           ;
      JavaScript - The Definitive Guide (4 th Edition);

Related articles: