Perera John
Perera John

Reputation: 73

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 (',','.','|');

Upvotes: 1

Views: 228

Answers (2)

Kavian K.
Kavian K.

Reputation: 1360

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

Upvotes: 1

baao
baao

Reputation: 73241

No need for regex, that's a simple indexOf operation, with even "better" results than the regex - e.g. 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}`);
  }
});

Upvotes: 2

Related Questions