简体   繁体   English

在字符串 javascript 的左右找到第一次出现的字符

[英]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.您能帮我在 javascript 中找到解决方案吗?

What I tried, I just search the exact string of array in mainString.我试过了,我只是在 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>');
                }
            });

Regex 101 demo: https://regex101.com/r/8MkCXs/1正则表达式 101 演示: https://regex101.com/r/8MkCXs/1

Regex that matches on brackets surrounding search strings joined into |与加入|的搜索字符串周围的括号匹配的正则表达式(OR), or just search strings joined into OR. (OR),或者只是搜索加入 OR 的字符串。

Added string escaping.添加了字符串 escaping。 Reference: https://stackoverflow.com/a/6969486/120242参考: 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 }

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这是另一种方法,您可以将字符串拆分为数组,然后比较元素,结果是所有输出的连接字符串,如果您要单独使用它们,我假设您会将它们存储在 object 中

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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何用JavaScript中的字符串替换第一次出现的字符? - How to replace the first occurrence of a character with a string in JavaScript? Javascript 从字符串中找出重复次数最多的字符 - Javascript find the most repetitive character occurrence from the string 查找字符串中字符的第二次出现 - Find second occurrence of a character in a string Javascript-查找单词在字符串中特定出现的位置(不是开头或结尾) - Javascript - Find position of specific occurrence of a word in a string (not first or last) 如何在Javascript中将字符串放在字符的左右 - How do I get the String to the Right and Left of a Character in Javascript 如何使用 JavaScript 动态方法从右侧删除/替换第一次出现的字符? - How to remove/replace first occurrence of character from the right using JavaScript dynamic approach? JavaScript RegEx-替换字符的第一个和最后一个出现 - JavaScript RegEx - replace first and last occurrence of a character 从第一次出现的字符中拆分字符串 - Splitting string from the first occurrence of a character 正则表达式每次在 JavaScript 中的字符串中重复时查找字符串中字符的偶数出现 - Regex to find even occurrence of a character in a string every time it repeats in a string in JavaScript javascript删除字符串中所有后续出现的字符 - javascript remove all succeeding occurrence of a character in string
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM