简体   繁体   中英

Search a specific word from Text Js , Including Special Characters

I have an Array which I loop through extracting word by word and comparing them to find any matches in a large text.

  var myString="I know the languages  C, C# and JAVA"
  var languages=['JAVA','C','Angular','C++','Python','C#'];
  for (var i=0;i<languages.length;i++){
      var myPattern = new RegExp('(\\w*'+languages[i]+'\\w*)','gi');
      var matches = myString.match(myPattern);
      if (matches != null)
      {
          console.log(languages[i]);
      }
  }

The Regex throws an Error when I reach C# or C++? Anything to extract both of these as well as others would be Appreciated. Note I Still need to escape other special characters such as (',','.','|');

No need for regex, that's a simple indexOf operation, with even "better" results than the regex - eg you could also indicate where the string was found in the text.

 const myString="I know the languages C, C# and JAVA"; const languages=['JAVA','C','Angular','C++','Python','C#']; languages.forEach(lang => { let x; if ((x = myString.indexOf(lang)) > -1) { console.log(`Found ${lang} at position ${x}`); } }); 

Also you can use String includes() Method. The includes() method determines whether a string contains the characters of a specified string. This method returns true if the string contains the characters, and false if not. Note that this method is case sensitive .

 var myString = 'I know the languages C, C# and JAVA', languages = [ 'JAVA','C','Angular','C++','Python','C#' ]; for ( var i = 0; i < languages.length; i++ ) { if ( myString.includes( languages[ i ] ) ) console.log( languages[ i ] ) } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM