javascript将字符串转换为css的安全类名

[英]javascript convert string to safe class name for css


I am sure this must of been asked before but can't find any in the search. What is the fastest way to ensure all non safe characters are removed from a string allowing it to be used in a CSS class name?

我确信之前一定要问过,但在搜索中找不到任何内容。确保从字符串中删除所有非安全字符以允许在CSS类名中使用的最快方法是什么?

6 个解决方案

#1


30  

I would replace anything that is not a lowercase letter or digit, and then I would add a special prefix to avoid collisions with class names you have used for other purposes. For example, here is one possible way:

我会替换任何不是小写字母或数字的东西,然后我会添加一个特殊的前缀,以避免与您用于其他目的的类名冲突。例如,这是一种可能的方式:

function makeSafeForCSS(name) {
    return name.replace(/[^a-z0-9]/g, function(s) {
        var c = s.charCodeAt(0);
        if (c == 32) return '-';
        if (c >= 65 && c <= 90) return '_' + s.toLowerCase();
        return '__' + ('000' + c.toString(16)).slice(-4);
    });
}

// shows "prefix_c_a_p_s-numb3rs-__0024ymbols"
alert("prefix" + makeSafeForCSS("CAPS numb3rs $ymbols"));

#2


12  

If you mean the following symbols

如果您的意思是以下符号

!"#$%&'()*+,./:;<=>?@[\]^`{|}~

then just replace them with nothing:

然后只需更换它们:

names = names.replace(/[!\"#$%&'\(\)\*\+,\.\/:;<=>\?\@\[\\\]\^`\{\|\}~]/g, '');

(I may have added an extra, or not enough, escape characters in there)

(我可能在那里添加了额外的或不够的转义字符)

Here is a quick demo.

这是一个快速演示。

But just so you know, not all of those symbols are "unsafe", you could just escape the symbol when targeting the class name (ref).

但只是你知道,并非所有这些符号都是“不安全的”,你可以在定位类名(ref)时转义符号。

#3


2  

I use this for my selectors, IDs or classes names:

我将它用于我的选择器,ID或类名:

String.prototype.safeCSSId = function() {
  return encodeURIComponent(
    this.toLowerCase()
    ).replace(/%[0-9A-F]{2}/gi,'');
}

#4


1  

You can try the urlify.js from django.

你可以试试django的urlify.js。

Get it from: https://github.com/django/django/blob/master/django/contrib/admin/static/admin/js/urlify.js

来自:https://github.com/django/django/blob/master/django/contrib/admin/static/admin/js/urlify.js

#5


0  

If anyone is interested in the coffee way of this:

如果有人对这种咖啡方式感兴趣:

window.make_safe_for_css = (name) ->
    name.replace /[^a-z0-9]/g, (s) ->
        c = s.charCodeAt(0)
        if c == 32 then return '-'
        if c >= 65 && c <= 90 then return '_' + s.toLowerCase()
        '__' + '000' + c.toString(16).slice -4

#6


0  

with jQuery:

用jQuery:

$.escapeSelector(stringToEscape);

Edit: Misunderstood the original question. This can be used e.g. when querying an element by class name but not for generating the class names.

编辑:误解了原来的问题。这可以用于例如按类名查询元素但不生成类名时。

智能推荐

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2011/10/02/3a67ae509563ed063cf234ed6fe8c79c.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告