nusu nusu - 3 months ago 7
Javascript Question

How to get specific part of a string in node.js?

I'm trying to do something fun with twitter API,
I want to search on twitter with #np (now playing) tag and split tweet by song name and artist name.

lets assume that it found this tweet

"Listen to It Will Happen by L.E.L #np on #SoundCloud"

I want to take song name, song artist and bind to variables.

and tweet can be something like this too

"just awesome :D #np Zombie (metal cover by Leo & Stine Moracchioli) https://youtu.be/4e4bAsQ4r30 via @YouTube"

I'm getting trouble with understanding regex so can somebody show me a proper way to do this 2 example?

Answer

There's hardly a pattern to find in random user input.
However, if most of it code generated by some source then there's often still find a pattern to be matched.

It probably needs to be separated by the source.
Since it makes it easier to deal with the capture groups.

var tweetString = "Listen to It Will Happen by L.E.L #np on #SoundCloud";
var myRegexp = /^(?:(.*)(?: by (.*))#\w+.* on #(\w+))$/;
var song = "";
var artists = "";
var messagesource = "";
match = myRegexp.exec(tweetString);
if (match != null) {
  song = match[1];
  artist = match[2];
  messagesource = match[3];
  console.log("song: " + song);
  console.log("artist: " + artist);
  console.log("messagesource: " + messagesource);
}

var tweetString = "just awesome :D #np Zombie (metal cover by Leo & Stine Moracchioli) https://youtu.be/4e4bAsQ4r30 via @YouTube";
var myRegexp = /^.*#\w+ (.*?)\(.*? by (.*?)\).* via @(\w+)$/;
var song = "";
var artists = "";
var messagesource = "";
match = myRegexp.exec(tweetString);
if (match != null) {
  song = match[1];
  artist = match[2];
  messagesource = match[3];
  console.log("song: " + song);
  console.log("artist: " + artist);
  console.log("messagesource: " + messagesource);
}

Comments