Skip to content

Instantly share code, notes, and snippets.

@suhailgupta03
Created August 18, 2023 15:10
Show Gist options
  • Save suhailgupta03/99050d7f6957dc599113233561739d8e to your computer and use it in GitHub Desktop.
Save suhailgupta03/99050d7f6957dc599113233561739d8e to your computer and use it in GitHub Desktop.
// Problem: Given a instagram post, we need to identify "all" the hashtags in the post
// Assumption: Hashtags will only have alphanumeric characters
// alphanumeric: [a-zA-Z0-9]
function extractHashTag(post) {
let pattern = /#[a-zA-Z0-9]+/g
// [a-zA-Z0-9] means any character from a to z, A to Z, 0 to 9
// + means one or more
const matchResult = post.match(pattern); // ["#beachday", "#day1"]
return matchResult;
}
let string = "Enjoying my day at the beach! #beachday #day1";
extractHashTag(string); // Output: ["beachday", "day1"]
@suhailgupta03
Copy link
Author

/*?= is a part of regular expression syntax in JavaScript. It is used to create a positive lookahead.
A lookahead is a type of zero-width assertion that allows you to match a pattern only if it is followed by another pattern, without including the second pattern in the match.
Here's an example:*/

let string = "apple banana mango";
let regex = /apple(?=\sbanana)/;
console.log(string.match(regex)); // Output: [ 'apple', index: 0, input: 'apple banana mango', groups: undefined ]

/*
In this case, the regex /apple(?=\sbanana)/ matches "apple" only if it is followed by " banana". The space before "banana" in (?=\sbanana) is necessary to match the space in the original string.
It's important to note that the lookahead pattern \sbanana (meaning "a space followed by 'banana'") is not included in the match result. The match only includes "apple". This is what's meant by "zero-width": the lookahead doesn't consume characters in the string, but only asserts whether a match is possible.
*/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment