How to pick a word within a string (phrase) in Node.JS

Asked

Viewed 3,589 times

1

I have a doubt,

have a string:

var frase = "Ola, bruno";

I need to take what is written down to the comma and then take what is written after the comma, for example:

var ABC = "Ola";
var EFG = "Bruno";

How to proceed?

  • And in case I have a phrase: "Hi Joao". How do I get Oi and Joao separately?

3 answers

1

Using the method indexOf.

The method returns the index of a given character in a string. From there it’s just working with this information.

Example with question code.

var frase = 'Ola, bruno';

var index = frase.indexOf(',');

var a = frase.substring(0, index);
var b = frase.substring(index + 2);

console.log(a);
console.log(b);

Or watch it work on repl.it.

0


Another way is by using the method split(), that divides a long string into parts delimited by a specific character and then creates an array with those parts.

var frase = 'Ola, Bruno, Fullstack, developer';		
var retorno = frase.split(",");
console.log( retorno[0] );
console.log( retorno[1] );
console.log( retorno[2] );
console.log( retorno[3] );

The ease of working with this method is very great.

Example in a loop:

var frase = 'Ola, Bruno, Fullstack, developer';

var frase_array = frase.split(',');

for(var i = 0; i < frase_array.length; i++) {
   console.log(frase_array[i]);
}

If you wish to remove the spaces

Use: frase_array[i].replace(/^\s*/, "").replace(/\s*$/, "");

var frase = 'Ola, Bruno, Fullstack, developer';

var frase_array = frase.split(',');

for(var i = 0; i < frase_array.length; i++) {
   frase_array[i] = frase_array[i].replace(/^\s*/, "").replace(/\s*$/, "");
   console.log(frase_array[i]);
}

0

Complementing @Leo Caracciolo’s response, both replace and split are String object methods, so they allow you to string methods, for example:

const meuTexto = "Raul, Felipe, de, Melo";
const regexWhiteSpace = /\s/g;

console.log(meuTexto.replace(regexWhiteSpace, '').split(','))

And if you know exactly what information you’re expecting to receive and want to create variables with each element in the array, you can use ES6 Destructuring, here’s an example:

const nomeCompleto = "Raul, Melo";
const regexWhiteSpace = /\s/g;
const [nome, sobrenome] = nomeCompleto.replace(regexWhiteSpace,'').split(',')

console.log('nome:',nome)
console.log('sobrenome:',sobrenome)

Browser other questions tagged

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