Jump to content

Need help pulling first word from field using grep


Recommended Posts

I have an old snippet of code from the email list days showing how to pull the first word from a string, but I can't seem to get it to work properly. Here is what I have:


var re = /(\w+)\s(\w+)/;
var str = Field("Name");
var newstr = str.replace(re, "$1");


It seems to work if there are only two words in the string, but if there are more I do not get the result I am expecting.


As an example, if the string is "one two", I get "one".

But if the string is "one two three four", I get "one three four".


I am guessing it might have something to do with greedy/lazy matching. I tried

var re = /(\w?)\s(\w+)/;

which worked on the online grep tester I was working with, but it didn't work in FP.


Any ideas?



Link to comment
Share on other sites

Thank you for the reply. Using indexOf is how I ended up getting this specific job to go through, but I am still trying to wrap my head around grep and why this search pattern doesn't work.
Link to comment
Share on other sites



I would like to make an improvement to your code.

With your code, in the event that the string DOES NOT contain a space, it will return "" (nothing).


How about...


var str = "one two three";

var position = str.indexOf(" ");

if ( position > 0 )

return str.slice (0,position);


return str;

Link to comment
Share on other sites

Yes, and you could add the Trim to suppress if the first character is a space

var str = Trim(" one two three");


Lance, returning to your grep, is it the same grep as under unix, powerful text handler, if you make it work, post back, i assume you would have to load the function/library to make it work under FP

Link to comment
Share on other sites


This topic is now archived and is closed to further replies.

  • Create New...