String-Manipulation Methods

Append

concat() concatenates one or more strings to another, returning the concatenated string as the result.


var stringValue = "hello ";
var result = stringValue.concat("world");
console.log(result);            //"hello world"
console.log(stringValue);       //"hello"
//from ww  w  . ja  v  a 2s .  co m
stringValue = "hello ";
result = stringValue.concat("world", "!");
console.log(result);            //"hello world!"
console.log(stringValue);       //"hello"

The addition operator (+) is used more often than the concat() method.

The code above generates the following result.

sub string

slice(), substr(), and substring() all three methods return a substring of the string. They do not alter the value of the string itself.

They all accept either one or two arguments.

  • The first argument is the position where capture of the substring begins.
  • The second argument, if used, indicates where the operation should stop. For slice() and substring(), this second argument is the position before which capture is stopped. For substr(), the second argument is the number of characters to return.
  • If the second argument is omitted, it is assumed that the ending position is the length of the string.
  • For the substring() method, all negative numbers are converted to 0. Consider this example:
  • For the slice() method, a negative argument is treated as the length of the string plus the negative argument.
  • For the substr() method, a negative first argument is treated as the length of the string plus the number, whereas a negative second number is converted to 0.

var stringValue = "hello world";
console.log(stringValue.slice(3));        //"lo world"
console.log(stringValue.substring(3));    //"lo world"
console.log(stringValue.substr(3));       //"lo world"
console.log(stringValue.slice(3, 7));     //"lo w"
console.log(stringValue.substring(3,7));  //"lo w"
console.log(stringValue.substr(3, 7));    //"lo worl"
//from   w ww  .j  a va  2 s  .  com
console.log(stringValue.slice(-3));         //"rld"
console.log(stringValue.substring(-3));     //"hello world"
console.log(stringValue.substr(-3));        //"rld"
console.log(stringValue.slice(3, -4));      //"lo w"
console.log(stringValue.substring(3, -4));  //"hel"
console.log(stringValue.substr(3, -4));     //"" (empty string)

The code above generates the following result.

trim()

The trim() method creates a copy of the string, removes all leading and trailing white space.


var stringValue = "    hello world    ";
var trimmedStringValue = stringValue.trim();
console.log(stringValue);            //"    hello world    "
console.log(trimmedStringValue);     //"hello world"
//  w w w.j av a  2  s . c  o  m

The code above generates the following result.





















Home »
  Javascript »
    Javascript Introduction »




Script Element
Syntax
Data Type
Operator
Statement
Array
Primitive Wrapper Types
Function
Object-Oriented
Date
DOM
JSON
Regular Expressions