Yeoman prompt: how generate a valid filename from a string?

邮差的信 提交于 2019-12-11 06:15:59

问题


Is there a method implemented in Yeoman or in Node to generate a valid filename from a string?

My aim is to replace accented letters by normal letters, spaces by dashes, etc.


回答1:


Basically, all you need is a function that removes special characters and perhaps replaces them using an arbitrary system.

One option was already named by passy, which is to make use of:

this._.dasherize(str)

Nevertheless, there are some additional options you might use. E.g., you might check out the underscore.string module, which provides some functions for this. From these, I'd highly recommend the slugify function:

From the documentation:

Transform text into a URL slug. Replaces whitespaces, accentuated, and special characters with a dash.

To provide an example:

_.slugify("Un éléphant à l'orée du bois")
=> 'un-elephant-a-loree-du-bois';

This should be exactly what you need, and still keeps a good readability.

Hope this helps.




回答2:


For Yeoman generators, the common way to handle this is to use this._.dasherize(str) in the JavaScript generator code or <%= _.dasherize(str) %> in templates. It doesn't take care of accented letters, but those should be valid filenames anyway.

console.log(this._.dasherize("some userProvided string")); 
// output: "some-user-provided-string"


来源:https://stackoverflow.com/questions/18083580/yeoman-prompt-how-generate-a-valid-filename-from-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!