2

I've cobbled together the following and it's working fine :

$('#url').val(filename.slice(0, -4).toLowerCase().replace(/[^\w\s]/gi, '').replace(/\s+/g, '-'));

But it's just so ugly. Can anybody suggest a cleaner way to do this?

What's happening :

1) strip the last 4 chars (.ext) from the filename from a fileinput

2) convert to lowercase

3) replace all non-alphanumeric characters except whitespace

4) replace whitespace with a hypen

End result is something like : my-wonderful-file

Can anybody make this look like less of a pig's ear?

spice
  • 1,442
  • 19
  • 35

2 Answers2

1

It looks like you want to create slug from a file name. Here is a nice reusable function.

function slugify(s) {
  s = s.replace(/[^\w\s-]/g, '').trim().toLowerCase();
  s = s.replace(/[-\s]+/g, '-');
  return s;
}

console.log(
  slugify("Filenam §4.ext".slice(0, -4))
);
wp78de
  • 18,207
  • 7
  • 43
  • 71
  • Thanks, nice clean solution but I'm only using this once on a single page so the function is a bit overkill. – spice May 04 '18 at 14:44
-1
Replace all non-alphanumeric characters with whitespace
<script>

  function numericFilter() {
      var demoString = "(7564)-//[hellow467%6]-jdjd@4F%&k";
      var regex = /\W/g;
      var replacedString = demoString.replace(regex, " ");
      var str = replacedString;
      var replaced = str.split(' ').join('+');
      document.write("The Original String was : " + demoString);
      document.write("<br>The replaced String : " + replaced);
    }
</script>
       <Ajax:ToolkitScriptManager runat="server" ID="ToolkitScriptManager1">
    </Ajax:ToolkitScriptManager>

    <input type="text" id="txb" onkeypress="javascript:return numericFilter()" />


</asp:Content>
M RAHMAN
  • 21
  • 1
  • If you're going to provide only code as an answer you should present it with a working example that solves OP's problem, or at least provide comments in your code explaining the solution. I also don't see how your solution simplifies OP's code, which is what they're asking for. – Adam Fratino May 04 '18 at 04:51
  • I appreciate the answer but this doesn't seem entirely relevant to my question. There's a whole bunch of non-relevant code in there and to be honest, if I had to choose between my ugly one liner and creating an entire function to do it, the one liner wins. – spice May 04 '18 at 05:00