yarek
yarek

Reputation: 12044

how to parse a JS usernames?

My string is:

"@john @jerry @kerry hello world"

My goal is to obtain an array:

["john","jerry","kerry", "hello world"];

Infact @ is the marker for username and the last array item is the rest of the string.

Any idea ?

Upvotes: 0

Views: 44

Answers (2)

Kasravnd
Kasravnd

Reputation: 107287

You can use following regex :

var str = "@john @jerry @kerry hello world";
var list = str.split(/(@\w+)/);

var str = "@john @jerry @kerry hello world";
var list = str.split(/(@\w+)/);
alert(list);

Upvotes: 0

adricadar
adricadar

Reputation: 10209

You can take the rest of the string and after that you can extract users and to append last string in array.

var data = "@john @jerry @kerry hello world";
// get rest of the string
var lastString = data.match(/ \w+/g).join('').trim();
// get users
var array = data.match(/@\w+/g).join('').split('@');
array = array.slice(1,array.length);
// add rest of string to end of array
array.push(lastString);

var data = "@john @jerry @kerry hello world";
// get rest of the string
var lastString = data.match(/ \w+/g).join('').trim();
// get users
var array = data.match(/@\w+/g).join('').split('@');
array = array.slice(1,array.length);
// add rest of string to end of array
array.push(lastString);

alert(array);

Upvotes: 1

Related Questions