lance Posted July 27, 2011 Share Posted July 27, 2011 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"); return(newstr);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? Thanks. Quote Link to comment Share on other sites More sharing options...
Andre Globensky Posted July 28, 2011 Share Posted July 28, 2011 Hi Lance, try this var str = "one two three four"; var newstr = str.substr(0,str.indexOf(" ")); return(newstr); //str.indexOf(" ") returns the number of characters of the first occurring word //str.substr(start position,length to return) Quote Link to comment Share on other sites More sharing options...
lance Posted July 28, 2011 Author Share Posted July 28, 2011 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. Quote Link to comment Share on other sites More sharing options...
scubajbc Posted July 28, 2011 Share Posted July 28, 2011 Andre, 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); else return str; Quote Link to comment Share on other sites More sharing options...
Andre Globensky Posted July 28, 2011 Share Posted July 28, 2011 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 Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.