How can we trim a sentence to three words

0
I have a requirement where the data is been fetched from API and hence by the title needs to be trimmed to three words...
asked
2 answers
4

You need some string manipulation for that. Use the find option to find the first location of the space so find($mystring, ‘  ‘) and put that in a integer variable for instance $spaceLocation. You then have the location of the space as an integer for that string. Then you can use substring with that value to cut the first word of that string so substring($myString, 0,  $spaceLocation) and put that in the result string. 

Now we need to find the second word so we now going to start with the second half of the string. The get the second part we use substring again but this time substring($mystring, $spaceLocation+1) and do not enter the second parameter because then you just get the last part of the string. And you need the +1  so you do not get a space as your first character. Store this again in a string variable. You can now do this process again and stop after the third time.

Regards,

Ronald

 

answered
0

Alternative: use the RegexReplaceAll java action in CommunityCommons and use 'trim($yourString)' as haystack parameter, the following regex as needleRegex parameter and replacement parameter '$1'

^((?:\S+\s+){2}\S+).*

 

answered