admin管理员组

文章数量:1168532

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);

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);
Share Improve this question edited Apr 7, 2016 at 22:17 Nick Zuber 5,6373 gold badges25 silver badges49 bronze badges asked Apr 7, 2016 at 22:15 Jony SJony S 1591 gold badge1 silver badge9 bronze badges 3
  • Do you always want the first two words? – Nick Zuber Commented Apr 7, 2016 at 22:18
  • Is there a reason you're using a regex? Seems a simple split+concat would suffice: var x = data.title.split(' ');var t = x[0] + "+" + x[1]; – fdomn-m Commented Apr 7, 2016 at 23:40
  • Just be aware if your string starts getting over 1MB a regex function for this can still handle this in a millionth of a second where the split join starts slowing down to hundredths or tenths of a second. Considering punctuation or other white space characters is another reason you might want to use regex. Split join does make it easy to change from space to '+'. – aamarks Commented Apr 30, 2018 at 22:12
Add a comment  | 

3 Answers 3

Reset to default 42

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

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])

This is my general function for first n words. Haven't tested it extensively but it is fast even on long strings because it doesn't use a global regex or split every word. You can fine tune the regex for dealing with punctuation. I'm considering a hyphen as a delimiter but you can move that to the word portion instead if you prefer.

function regFirstWords(s, n) {
    // ?: non-capturing subsequent sp+word.Change {} if you want to require n instead of allowing fewer
    var a = s.match(new RegExp('[\\w\\.]+' + '(?:[\\s-]*[\\w\\.]+){0,' + (n - 1) + '}')); 
    return  (a === undefined || a === null) ? '' : a[0];
}

To satisfy the OP's request to replace with '+'

regFirstWords('ABC XYZ PQRS - www.aaa.tld',2).replace(/\s/g,'+')

本文标签: javascriptHow to get first 2 wordsStack Overflow