How to get a word inside a string (phrase) in Node.JS

1

I have a question,

I have a string:

var frase = "Ola, bruno";

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

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

How to proceed?

    
asked by anonymous 12.05.2017 / 22:57

3 answers

0

Another way is to use the split() method, which 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 large.

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 want 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]);
}
    
12.05.2017 / 23:28
1

Using the indexOf method.

The method returns the index of a given character in a string . From there, just work 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 see working on repl.it.

    
12.05.2017 / 23:01
0

Complementing @Leo Caracciolo's response, both replace and split are methods of the String object, so they allow you to do method chaining, 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's 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)
    
13.05.2017 / 19:22