How to get the first word of a string with jquery?

4

Ex: "First string word"

I want to get the word "First"

    
asked by anonymous 07.01.2017 / 17:34

4 answers

6

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);
    
07.01.2017 / 17:45
4

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.

    
07.01.2017 / 17:57
2

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);
    
07.01.2017 / 17:51
2

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);
    
07.01.2017 / 18:19