Umesh Sehta
Umesh Sehta

Reputation: 10683

find first occurrence of character in left and right of string javascript

I need a solution to my exceptional requirement. I have a string like

var mainString="[Avg Advisor Count by College numerator][Advising by college denominator] nominator count";

and have an array variable.

var searchArray = ["Advisor Count","Advising"];

I need to search the array elements in main string and if any of element match in main string then find the left first occurrence of the "[" of the string and right first occurrence of the "]" and encapsulate into a span.

As the first element of array finds in string "Advisor Count" and the second element also finds in the string. So the result would be

result = "<span>[Avg Advisor Count by College numerator]</span><span>[Advising by college denominator]</span>"

Can you please help me to find a solution for this in javascript.

What I tried, I just search the exact string of array in mainString. but don't get an idea of how to search occurrence of "[" in left and right of search string.

var mainString = calculatedFields["formula"][i];
            calculatedArray.forEach(function (value) {
                if (fm.indexOf('[' + value + ']') > -1)
                    fm = replaceAll(fm, '[' + value + ']', '<span style="color:#f29343">[' + value + ']</span>');
                else {
                    fm = replaceAll(fm, value, '<span style="color:#f29343">' + value + '</span>');
                }
            });

Upvotes: 0

Views: 839

Answers (2)

Sven.hig
Sven.hig

Reputation: 4519

Here is a different approach, you can split the string into an array and then compare the elements, the result is a concat string of all outputs, if you are going to use them individually which i assume you will store them in an object instead

var mainString="[Avg Advisor Count by College numerator][Advising by college denominator] nominator count something";
var searchArray = ["Advisor Count","Advising"];
function producespan(mainString,searchArray){
 var result=''
 xarrwithbrk=mainString.split(']').filter(x=>x.includes('['))
 xarrwithspa=mainString.split(']').filter(x=>!x.includes('[')).flatMap(x=>x.split(' '))
searchArray.forEach(element => {
  xarrwithbrk.forEach(str=>{
    if(str.includes(element)){
      result+="<span>"+str+"]</span>"
   }})  
   xarrwithspa.forEach(str=>{
    if(str.includes(element)) result+="<span>"+str+"</span>"
   })
}); 
      return result
}
console.log(producespan(mainString ,searchArray))

Upvotes: 1

user120242
user120242

Reputation: 15268

Regex 101 demo: https://regex101.com/r/8MkCXs/1

Regex that matches on brackets surrounding search strings joined into | (OR), or just search strings joined into OR.

Added string escaping. Reference: https://stackoverflow.com/a/6969486/120242

var mainString="[Avg Advisor Count by College numerator][Advising by college denominator] nominator count";
var searchArray = ["Advisor Count","Advising","count"];

searchArray = searchArray.map(escapeRegExp)

console.log(
mainString.replace(
new RegExp(String.raw`(\[[^\]]*(?:${searchArray.join('|')})[^\]]*\])|(${searchArray.join('|')})`,'g'),'<span>$1$2</span>'
)
)

function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}

Upvotes: 1

Related Questions