How to find substring in a string and return a new string with a number of characters surrounding the substring - Javascript -


first of new javascript.

my question:

let's have string this

var str = "john doe in name used people no identity"; 

i need function 3 arguments like

pullsubstring(text, string, number) 

it return new string this

*length of number in strings* + string + *length of number in strings* 

to more specific here's example :

if call function this

pullsubstring("for", "john doe in name used people no identity", 5) 

the result "used peop".

you can use function:

function pullsubstring(searched,text,borderslenght) {     var idx = text.indexof(searched);     if (idx == -1 )         return "";      var startfrom = idx-borderslenght;     var endat = idx + borderslenght + searched.length;      if (startfrom < 0)         startfrom=0;      if (endat > text.length-1)         endat = text.length-1;      return text.substring(startfrom,endat);  } 

you have choose return when searched string not found (my function return empty string), or when adding n character before or after found text take before start or after end of text (my function trim returned text in these 2 cases).


Comments

Popular posts from this blog

Unable to remove the www from url on https using .htaccess -