Krish
Krish

Reputation: 11

Check if the String ends with a pattern from the List of Arrays - JavaScript

I have a array of Strings which are typically urls of the pages. I need to do certain action only on few of the pages (Applying Styles)

So I have written the below code

const location = useLocation();
const [margin, setMargin] = useState();

const urls = [
  'https://www.website.com/abc/',
  'https://www.website.com/xyz',
  'https://www.website.com/123/',
  'https://www.website.com/456/',
];

useEffect(() => {
  if (urls.includes(window.location.href)) {
    setMargin('350px');
  } else {
    setMargin('36px');
  }
}, [location.pathname]);

But we also has a list of multiple localhost urls, and Preview URLs and the I the array keeps growing. I am trying to find a alternate way where I can play around using endsWith

I am trying something like,

let ends = [/xyz/, /123/, '/abc/' '/def/']

useEffect(() => {
  let currentURL = window.location.href
  if (currentURL.endsWith(...ends)){
    console.log("Show Margin", currentURL)
    setMargin('350px');
  } else {
    setMargin('36px');
    console.log("Dont show margin", currentURL)
  }
}, [location.pathname]);

So this can help the array to be shorter. But I am unable to use endsWith and compare it with the array. Could someone help me on this, or is there a better way to get this done?

Upvotes: 1

Views: 556

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521239

You may form a regex alternation of the endings and use match() instead of endsWith():

let ends = [/xyz/, /123/, '/abc/', '/def/'];
let regex = new RegExp("(?:" + ends.join("|") + ")$");

useEffect(() => {
    let currentURL = window.location.href
    if (currentURL.match(regex)) {
        console.log("Show Margin", currentURL)
        setMargin('350px');
    }
    else {
        setMargin('36px');
        console.log("Dont show margin", currentURL)
    }
}, [location.pathname]);

Upvotes: 0

Related Questions