Ex: "First string word"
I want to get the word "First"
Ex: "First string word"
I want to get the word "First"
You do not really need jQuery, "with jQuery" would be the same:
var strg = 'Primeira palavra da string';
var word_one = strg.split(' ')[0];// separar str por espaços
console.log(word_one);
A very simple way is to take the position of the space with indexOf
and extract with substring
:
primeira = texto.substring(0, texto.indexOf(" "));
Demo:
var texto = "Teste de extração com espaço";
var primeira = texto.substring(0, texto.indexOf(" "));
console.log( primeira );
And here is a little trick to not come empty the result, if it is a word without spaces:
var texto = "Teste";
var primeira = texto.substring(0, (texto + " ").indexOf(" "));
console.log( primeira );
Changing texto.indexOf(" ")
by (texto + " ").indexOf(" ")
we always guarantee a space at the end of the test, to solve the single word case.
You can do this by breaking the sentence down and using .shift()
.
var strg = 'Primeira palavra da string';
var word_one = strg.split(' ').shift();
console.log(word_one);
Or via regular expression and using .shift()
.
var strg = 'Primeira palavra da string';
var word_one = strg.match(/^[^\s]+/).shift();
console.log(word_one);
One suggestion for text to begin with spaces is to use the trim before separating the string.
var str = ' Primeira palavra da string';
var primeira = str.trim().split(' ')[0];
console.log(primeira);