Reputation: 1227
I was wonder the best way one could look for a specific phrase in a string and then take everything after it and store that in a new variable. For example if...
var str = 'hello how are you doing the what is a dinosaur search Jim carrey';
Everything after 'search ' or 'search for ', in this case 'Jim carrey' should be stored in a new var— let's call it val.
Also, if there are two or more instances of the phrase 'search ' or 'search for ' then only store what is after the latest one in val.
For example: if str = 'welcome I am search pie recipie search quick chili recipie' then val would be 'quick chili recipie' Or If str = 'Today is 78 degrees search good weather and sunny in other words a perfect day for search for when does summer end' then val would be 'when does summer end'.
Upvotes: 3
Views: 2711
Reputation: 2725
Try this RegExp :
var str = 'Today is 78 degrees search good weather and sunny in other words a perfect day for search for when does summer end';
var arr = str.split(/ search (for){0,1}/);
alert(arr[arr.length-1]);
Upvotes: 6
Reputation: 54072
try
var str = "welcome I am search pie recipie search quick chili recipie";
var m = str.split('search');
alert(m.slice(-1));
or
str.split('search').pop() // will do same thing
Upvotes: 1
Reputation: 5018
Legendinmaking's answer returns the phrase with a space at beginning and to return everything after search or search for use this
var str = 'welcome I am search pie recipie search quick chili recipie';
var param='search';
var param1='search for';
var n=str.lastIndexOf(param);
var n1=str.lastIndexOf(param1);
n=Math.max(n,n1);
alert(str.substring(n+param.length + 1,str.length));
Upvotes: 1
Reputation: 3453
Try this
var str = 'welcome I am search pie recipie search quick chili recipie';
var param='search';
var n=str.lastIndexOf(param);
alert(str.substring(n+param.length,str.length));
Upvotes: 0
Reputation: 13174
i am not sure it is the best way of doing it but it works and you can try to change srt value at jsbin: http://jsbin.com/uguzup/1/edit
var str = 'Today is 78 degrees search good weather and sunny in other words a perfect day for search for when does summer end';
var val = str.split('search for').slice(-1)[0].split('search').slice(-1)[0]
Upvotes: 0