开发者

The regular expression doesn't work

开发者 https://www.devze.com 2023-01-13 03:37 出处:网络
Trying to replace any non alpha-numeric characters with a hyphen. Can\'t see why it shouldn\'t be working. It returns the original string unchanged.

Trying to replace any non alpha-numeric characters with a hyphen. Can't see why it shouldn't be working. It returns the original string unchanged.

item开发者_StackOverflow社区.mimetype = "image/png";

var mimetype = item.mimetype.toLowerCase().replace("/[^a-z0-9]/g",'-');


Remove the quotes around the regex.

As written, Javascript is looking for the string "/[^a-z0-9]/g"

// This works
"image/png".toLowerCase().replace(/[^a-z0-9]/g,'-'); 

// And if writing unquoted regular expressions makes you feel icky:
"image/png".toLowerCase().replace(new RegExp("[^a-z0-9]", "g"), '-');

// And if I might do a full rewrite:
"image/png".toLowerCase().replace(/\W/g, '-');

More here


You've put a string instead of a regex. Do this:

.replace(/[^a-z0-9]/g,'-');
0

精彩评论

暂无评论...
验证码 换一张
取 消