1

I'm trying to search a mixed string for specific text. at the moment, the following is only searching the start, and end of a string. I want to basically search for a word if it exists anywhere in the string.

example string to be searched: dMc67FkhyMzzEmjELDcMEfqPJkKbF4jHis

I might want to search for example for: john

at the moment, here are the relevant pieces of code. Any thoughts?

I call my code via command like: "node file.js John bob Walter" , this gives me the ability to pass any number of strings in.

const lookFor = process.argv.slice(2).map(function (f) { return f.toLowerCase().replace(/[^a-zA-Z0-9]/g, '') })

......

var re = '^(d)(' + lookFor.join('|') + ')(.+)$|^(d.+)(' + lookFor.join('|') + ')$'

......

const regexp = new RegExp(re, 'I')

......

var test = regexp.exec(account.address)

Search should be case insensitive. Any ideas for the best way to accomplish this? I can't get my head around it.

The last part I will need to work out after that is, to highlight the string I searched for, when printing the whole string to console.

Vacek
  • 179
  • 1
  • 12
  • Do you *have* to use a regex for this? Pretty sure the code would look a lot cleaner if you could use a different method – CertainPerformance Dec 26 '18 at 01:35
  • Possible duplicate of [How to check whether a string contains a substring in JavaScript?](https://stackoverflow.com/questions/1789945/how-to-check-whether-a-string-contains-a-substring-in-javascript) – Heretic Monkey Dec 26 '18 at 01:37

1 Answers1

1

Just use String.prototype.includes():

var str = "dMc67FkhyMzzEmjELDcMEfqPJkKbF4jHis";
var search = "john";
console.log(str.includes(search)); //Should return false

var str = "dMc67FkhyjohnMzzEmjELDcMEfqPJkKbF4jHis";
var search = "john";
console.log(str.includes(search)); //Should return true

And if you want to remove the case difference (this won't find jOhn, for example) you could use String.prototype.toLowerCase():

var str = "dMc67FkhyMzzEmjJOHnELDcMEfqPJkKbF4jHis";
var search = "john";
console.log(str.toLowerCase().includes(search)); //Should return true
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
  • Thanks Jack. I just updated the description. Important to note I can pass in multiple strings. And not just one string I'm searching, but thousands via a loop. – Vacek Dec 26 '18 at 01:48