Splitting the String in JavaScript
Var FullName = John, Cooper;
Where LastName = John and FirstName = Cooper
.
How can i split the string FullName and开发者_运维问答 display my two TextField values with LastName and FirstName.
FullName.split(","2);
var splitted = "john, cooper".split(', '),
lastName = splitted[0],
firstName = splitted[1];
First, strings in JavaScript have a "
before and after it. Second, it is var
and not Var
.
Say you have
var FullName = "John, Cooper";
Then you can code like this to split:
var FirstName = FullName.split(", ")[1];
var LastName = FullName.split(", ")[0];
Just because I like the pattern:
var fullname = "John, Cooper";
(function(first, last) {
console.log(first, last);
}).apply(null, fullname.split(/,\s*/));
explanation:
The above code creates a function expression
(that is done by wrapping the function into the parenthesis). After that it self-invokes that created function immediately by calling .apply()
from the Function object
(remember, most things in ECMAscript are objects, so are functions). Any function inherits from Function
and the .apply()
method takes two arguments. 1. a context (=object) for the this
parameter in the invoked method and 2. an argumentslist as Array
. Since .split()
returns an Array
we use that to directly pass the result from .split()
as arguments.
Var FullName = 'John, Cooper';
name = FullName.split(',');
name[0]---//Jhon;
name[1]----//cooper
console.log(FullName.split(','));
精彩评论