John Cooper
John Cooper

Reputation: 7651

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);

Upvotes: 0

Views: 121

Answers (4)

jAndy
jAndy

Reputation: 236132

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.

Upvotes: 2

K6t
K6t

Reputation: 1845

Var FullName = 'John, Cooper';
name   =  FullName.split(',');
name[0]---//Jhon;
name[1]----//cooper
console.log(FullName.split(','));

Upvotes: 0

davin
davin

Reputation: 45555

var splitted = "john, cooper".split(', '),
    lastName = splitted[0],
    firstName = splitted[1];

Upvotes: 5

pimvdb
pimvdb

Reputation: 154948

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];

Upvotes: 3

Related Questions