0

I want to find a specific chunk of a string using regular expression. I have already a name in this string like aside-canvas. So, When I check for aside it returns true string.match(/aside/) But it should return false. Because it has aside-canvas not just aside.

How can I do that with regular expression dynamically.

let 
    string = 'aside-canvas othersName';
//checking for only aside not aside-canvas, so it should return false

1 Answers1

2

If you are trying to match an exact string, you don't even need a regex for that:

let string = 'aside-canvas other others';

console.log(string.includes('aside-canvas'))

If you want to make sure that different class names in the list are treated separately:

let string = 'aside-canvas other others';

console.log(string.split(' ').includes('aside'))

let string2 = 'aside-canvas other others aside';

console.log(string2.split(' ').includes('aside'))

Or if you are really married to the regex idea:

(?:^| )aside(?:$| ) will check if it's either the start or has a space (to keep boundaries between classes consistent). Then the class name of interest aside. Then if it's the end of the string or a space to make sure that's the end of the class name.

let string = 'aside-canvas other others';
let regex = /(?:^| )aside(?:$| )/
console.log(regex.test(string))

let string2 = 'aside-canvas other others aside';

console.log(regex.test(string2))
let word = 'anotherClassName';

let dynamicRegex = new RegExp(`(?:^| )${word}(?:^| )`);
console.log(dynamicRegex);

If you want to make the regex dynamically, just create a new instance of RegExp:

Just note that whatever is in word will be treated as regex rather than text. So if you want to match * for instance, you need to escape it out.

let word = 'anotherClassName';
let dynamicRegex = new RegExp(`(?:^| )${word}(?:^| )`);
Zachary Haber
  • 10,376
  • 1
  • 17
  • 31
  • are you aware of the existence of regex word boundaries? – Peter Seliger May 29 '20 at 14:17
  • @PeterSeliger, yes, but `-` also counts as a word boundary, so I had to avoid using them. – Zachary Haber May 29 '20 at 14:18
  • I want to make it dynamically. I mean the ```aside``` class could be anything else then how can I check it ```let word = 'anotherClassName';``` –  May 29 '20 at 14:21
  • Can you please suggest me any good source to learn regular expression? –  May 29 '20 at 14:26
  • Where I learned it from was the textbook: `Mastering Regular Expressions`, but [Reference - What does this regex mean?](https://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean/22944075#22944075) is a good resource with links to some tutorials gathered by users here. – Zachary Haber May 29 '20 at 14:30
  • @ZacharyHaber Do you know Jeffrey Friedl? –  May 29 '20 at 14:36