On the strings in JavaScript and Java

Source: Internet
Author: User
Tags string methods truncated

JavaScript string manipulationfirst, the creation of a string

There are several ways to create a string.

1. The simplest is to enclose a set of characters in quotation marks. var mystr = "Hello, string!" ;//  There is no difference between single and double quotes in JS

2, you can use the following statement: var myStr1 = new String ("Hello, string!");

Console.log (typeof mystr);//"string" Console.log (typeof myStr1);//"Object"

The above output shows: MyStr is a simple type variable, MYSTR1 is an object

second, the string "Length" Method  

1, the concatenation of strings

Concat () or "+"

2, the interception of strings

1. String.substring (from, to) returns the truncated string

The parameters are the truncated index positions, respectively. Note: The index of the parameter to can be greater than, less than, equal to the location of from, can also be omitted, does not support negative numbers!

var str = "Colin is a Desinger"; section = str. substring (0, 4);  "coli" section = str. substring (4, 0);//  "coli" section = str. substring (1, 1);  "" section = str. SUBSTRING ( -2, 4);  "coli" str. SUBSTRING (0, 4);//"Coli"
Console.log (str) //"Colin is a Desinger";

2, String.slice (start, end) returns the truncated string

  The argument start indicates the starting position of the substring, and if it is a negative number, it can be understood as the beginning of the countdown, for example-3 means starting from the last third; The parameter end represents the end position, as with start, it can also be negative, meaning it also indicates the end of the countdown. Slice () parameter can be negative, so more flexible than substring (), but less tolerant, if start is larger than end, it will return an empty string

var str = "Colin is a Desinger"//  "coli"//  "N is a Desinge" section = str. Slice (1, 1);  //   ""str. Slice (0, 4); // ""console.log (str); //"Colin is a Desinger"

3, substr (Start,len) returns the truncated string

Parameter start is the starting position, Len is the length of the substring note: This function is not advocated (I do not know the reason for the moment)

  The "position" function of the string

1, Str.indexof (searchvalue,fromindex) returns the index (from left to right) of the first occurrence of a substring in a string. If there is no match, returns-1.

2. Str.charat (index) returns the character at the specified position

3. str.charcodeat (Index) returns the Unicode encoding of the character at the specified position. This return value is an integer between 0-65535.

4, Str.fromcharcode (numx,numx,..., numx) can accept a specified Unicode value, and then return a string.

Four , the "regular" function of the string

1. the most powerful JS string function --str.replace (regexp/substr,replacement)

The change method is used to replace some characters with some character in a string, or to replace a substring that matches a regular expression.

  The parameter replacement is a string : For regular replace, a special token is specified for $:

      1. $i (i:1-99): Represents the text that matches a left-to-right regular subexpression.
      2. $&: Represents the full text that matches the regular expression.
      3. $ ' (': Toggle Skill Key): Represents the left-hand text of a matching string.
      4. $ ' (': Single quotation mark): Represents the right-hand text of a matching string.
      5. $$: Represents $ transfer.
"Boy & Girl". Replace (/(\w+) \s*&\s* (\w+)/g, "$ & $")//girl & Boy ' Boy '. Replace (/\w+/g, "$&-$&" )//Boy-boy "JavaScript". Replace (/script/, "$&! = $ '")//javascript! = Java "javascript". Replace (/java/, "$&$" is ")//JavaScript is script

  The second argument is a function:

In ECMASCRIPT3 it is recommended to use a function method, implemented in JavaScript1.2. When the Replace method executes, the function is called every time, and the value is returned as the new value to replace.

The function parameters are specified:

    1. The first parameter is a full-text ($&) of each match.
    2. The intermediate argument is a subexpression that matches the string, with an unlimited number. ($i (i:1-99))
    3. The second-to-last argument matches the position of the matching text string.
    4. The last parameter represents the string itself.
String.prototype.capitalize = function () {     return This.replace (/(^|\s) ([A-z])/g, function (M,P1,P2) {return p1+ P2.touppercase ();     } ); };

2, Str.match (rgexp)

if the match method does not find a matching, NULL is returned . If a match is found , the match method returns an array and updates the properties of the global RegExp object to reflect the matching result. G ) is not set, the array element 0 contains the entire match, and the element 1 to   n   contains any one of the sub-matches.  exec Method (Regular Expression) (JavaScript) when t He global flag is not set. " This behavior is the same as the  exec method (regular expression) (JavaScript)   When the global flag is not set. n   contains all occurrences of the match. match   method has two attributes: input   and   index .  input property contains the entire searched string. " The >input  property contains the entire string being searched.  index property contains the position of the matched substring within, the complete searched string. " The >index  property contains the position of a substring that matches the entire searched string. If flag iis set, the search is case insensitive.

v. Other common methods

1,Stringobj.trim () removes leading spaces, trailing spaces, and line terminators from the string.

2, str.tolowercase () lowercase

3, str.touppercase () uppercase

。。。。。。。

Six, String properties

1. String.constructor Specifies the function that creates a string.

var x = new String (), if (x.constructor = = string)    document.write ("Object is a string."); else    document.write ("Object is not a String."); /output://Object is a String.

2. String.prototype returns a reference to the prototype for the class of the string.

Provides a basic set of functions for a class of objects with the prototype property. The new instance of the object "inherits" the behavior that gives the object a prototype.

For example, to add a method to a string object that returns the value of the last element of a string, declare the function, add it to String.prototype , and use it.

function String_last () {    return This.charat (this.length-1);} String.prototype.last = String_last;var myString = new String ("Every Good Boy Does fine");d Ocument.write (Mystring.last () );//Ou
  The JavaScript string is immutable--"The length of the string cannot be modified."

First, look at the following code:

var a= "Java" a=a+ "script" Console.log (a);//"JavaScript"

Does the string content of variable a change from "Java" to "JavaScript", not to prove that the JS string is mutable? (I also think so when I started to learn JS)

Remember: you have to understand that the area in memory cannot be changed. The memory address referred to in the first variable A, not the memory address referred to in the two row variable a

Finally, take a look at the following code:

var lang = ' java '; lang[lang.length-1] = ' S '; lang[lang.length-1] = ' C '; console.log (lang);//"java" var arr = [' J ', ' a ', ' V ', ' A '];arr[arr.length-1] = ' s '; Console.log (arr);//[' J ', ' a ', ' V ', ' s '];
  Eight, skillfully using the array to achieve efficient concatenation of JS array 
var start = new Date (); var str = ""; for (var i = 0; i < 1000000; i++) {     str + = "Test";} var end = new Date ();d Ocument.writeln ("+ stitching string, Time:" + (End.getmilliseconds ()-start.getmilliseconds ())); Document.writeln ("<br/>"), var begin = new Date (), var arry = new Array (), for (var i = 0; i < 1000000; i++) {     A Rry.push ("Test");} Arry.join (""); var stop = new Date ();d Ocument.writeln ("array concatenation string, time consuming:" + (Stop.getmilliseconds ()-Begin.getmilliseconds ()));
  nine, regression string creation

Let's look at the following code:

var str= "Colin"; var str1=new String ("Colin"); str.substring (0,2); STR basic type data, why can I call the substring method? Str1.substring (0,2); Str1 Object

Here is why the STR variable has substring method, I am not very clear at the moment. I would like to think that in the execution of the "str.substring ()" Code for a moment, Str becomes an object???!!

Java string manipulationfirst, the creation of a string

1, the direct assignment String str= "Hello";//must be double-quoted here

2. Use the New keyword string str=new string ("Hello")

Similarities and differences between the two ways of creation:

  

Conclusion: when creating a string in the second way: the system creates two "Hello" in the heap memory, but one "hello" does not have a corresponding stack memory guideline, consumes extra memory, and the garbage space waits to be reclaimed.

So it is recommended to create a string in the first way

second, the common method of the string

The names and usages of many string methods in Java are similar to the JS string method.

1, public char charAt(int index) returns the value at the specified index char

2. public string concat(String str) connects the specified string to the end of this string.

3, public int indexOf(string Str,int fromIndex) returns the index of the first occurrence of the specified substring in this string.

。。。。

I think there are a few fun ways to be aware of:

1, public int Length () returns the lengths of this string here and JS have a subtle difference

2. Public boolean startsWith(string prefix, int toffset) tests whether the substring starting at the specified index starts with the specified prefix.

3, public boolean endsWith(string suffix) tests whether this string ends with the specified suffix.

4, public char[] ToCharArray() converts this string to a new character array.

5, public void getChars(int srcbegin, int srcend,char[] Dst,int dstbegin) Copies the character from this string to the target character array.

  three, the character string to play the immutability

Just look at the picture, don't explain it much.

Iv. "Alternative Strings" 

1, StringBuffer sb=new stringbuffer ("DF");//variable length,

Common methods:

Append ()

Insert ()

Replace ()

IndexOf ()

2, StringBuilder SB =new StringBuilder ("DSF")

Ideal for single thread speeds faster than StringBuffer

When considering thread safety, it is better to use StringBuffer

On the strings in JavaScript and Java

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.