1

Is there a pattern that is able to indetify whether a string is a common word or a regular expression? Or is there a JavaScript tool that does It?

A regular expression can be created from a string and usually have this form: [a-zA-z] * \ d?

And a common word may be: 'cat', 'dog', etc. I want to know whether a value of a string is a regular expression and not a common word.

In another words i can write a regex that indentify a regex?

  • 4
    many common words are also valid regular expressions. what problem do you want to solve? – kennytm Jun 01 '17 at 18:41
  • As long as you don't assume these kind of strings `/user8099525/` a regex, then yes, to some extent. – revo Jun 01 '17 at 18:44
  • No string is a "regular expression" in javasript unless it is parsed using the RegExp constructor. Many strings can be made into regular expressions. Common words can be made into regular expressions, so if you are asking if there is a way to be able to distinguish between the two (visually) based on some pattern - no. If you are asking if you can determine if some variable is a string or regex - of course but that's type checking and has nothing to do with the underlying pattern of characters. – Damon Jun 01 '17 at 18:48
  • In regex? Don't try. You can check if "".search(str) throws an error to see if the str can be compiled to a valid regex though. – Tezra Jun 01 '17 at 19:02
  • 2
    'cat' and 'dog' are also valid regex. They match those exact sequence of letters. Therefor, all common words are valid regex. – Tezra Jun 01 '17 at 19:03

1 Answers1

0

Assuming you want to target a source (ex: an article) and want to check which words are used most commonly in that source:

Assume the whole block of texts in the articles are in one string, assigned to variable "str":

// Will be used to track word counting
const arrWords = [];
// Target string
const str = 'fsdf this is the article fsdf we are targeting';
// We split each word in one array
const arrStr = str.trim().split(' ');

// Lets iterate over the words
const iterate = arrStr.forEach(word => {
  // if a new word, lets track it by pushing to arrWords
  if (!arrWords.includes(word)) {
    arrWords.push({ word: word, count: 1 });
  } else {
    // if the word is being tracked, and we come across the same word, increase the property "count" by 1
    const indexOfTrackedWord = arrWords.indexOf(word);
    arrWords[indexOfTrackedWord].count++;
  }
});

// Once that forEach function is done, you now have an array of objects that look like this for each word: 
arrWords: [
  {
    word: 'fsdf',
    count: 2
  },
  {
    word: 'this',
    count: 1
  },
  // etc etc for the other words in the string
];

Now you can just console.log(arrWords) to look at the results!

Chris
  • 973
  • 1
  • 8
  • 20