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

Asked

Viewed 4,863 times

7

Ex.: "First word of string"

I want to take the word "first"

4 answers

9


In reality you don’t even 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);

6

A very simple way is to take the position of space with indexOf and extract with substring:

primeira = texto.substring(0, texto.indexOf(" "));

Demonstration:

var texto = "Teste de extração com espaço";
var primeira = texto.substring(0, texto.indexOf(" "));

console.log( primeira );

And here 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 the texto.indexOf(" ") for (texto + " ").indexOf(" ") we always guarantee a space at the end of the test, to solve the case of the single word.

3

You can do that by breaking the phrase into pieces 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);

  • 1

    Always big (+1, I didn’t even remember the .shift()

2

A hint if the text starts with spaces is to use the method Trim before separating the string.

var str = '  Primeira palavra da string';
var primeira = str.trim().split(' ')[0];
console.log(primeira);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.