Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get first 2 words?

Let data.title be ABC XYZ PQRS - www.aaa.tld. Output needs to be like this ABC+XYZ

i've tried this:

var t = data.title.split(' ').join('+');
t = t.replace(/(([^\s]+\s\s*){1})(.*)/,"Unknown");
 $("#log").text(t);
like image 929
Jony S Avatar asked Apr 07 '16 22:04

Jony S


People also ask

How do I get the first two words in Excel?

In the Formulas Helper dialog, please do as follows: Select Text from the Formula type drop-down list; Select Extract the nth word in cell in the Choose a formula list box; In the Cell textbox, specify the cells that you will extract words from, and enter the number you want to extract word based on in The Nth textbox.

How do I pull the second word in Excel?

(1) Select Text from the Formula type drop-down list; (2) Click to highlight Extract the nth word in cell in the Choose a formula list box; (3) In the Cell box, specify the cell that you will extract word from; (4) In The Nth box, specify the number.


2 Answers

Here is one way to do it, no regex though, it only grabs the first two words and must have a space between those words.

First we split into and array, then we slice that array from the 0 index to 2(exclusive) or 1, and finally we join them with a '+':

var x = 'ABC XYZ PQRS';

var y = x.split(' ').slice(0,2).join('+');

// y = "ABC+XYZ"

Working Fiddle

like image 155
omarjmh Avatar answered Sep 30 '22 09:09

omarjmh


Try using .match() with RegExp /([\w+]+)/g; concatenate first match, + character, second match

var matches = "ABC XYZ PQRS - www.aaa.tld".match(/([\w+]+)/g);
console.log(matches[0] + "+" + matches[1])
like image 28
guest271314 Avatar answered Sep 30 '22 07:09

guest271314