Question

I want to get the file root's location by using keywords such as below. But both keywords give me different result.

<script type="text/javascript" src="http://localhost/website/core/core.js"></script>
<script type="text/javascript" src="http://localhost/website/local/ready.js"></script>

$('script[src$="core.js"]').attr('src').split('core')[0];
// get this  --> http://localhost/website/

$('script[src$="ready.js"]').attr('src').split('local')[0];
// get this  --> http://

I am after http://localhost/website/ as my result.

Is it possible to add regex into the split function such as below?

$('script[src$="core.js"]').attr('src').split('core|local')[0];
Was it helpful?

Solution

Use a regular expression that matches word boundaries, so that local doesn't match localhost.

$('script[src$="core.js"]').attr('src').split(/\b(?:core|local)\b/)[0];

OTHER TIPS

You can use:

$('script[src$="core.js"]').attr('src').split(/\/core\/|\/local\//)[0]+'/'

What the above does is:

  1. Split by /core/ or /local/ whichever it finds first
  2. Append a / at the end since that is not part of the first split
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top