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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7627000/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 00:44:36  来源:igfitidea点击:

javascript convert string to safe class name for css

javascriptjquery

提问by John Magnolia

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 类名中使用的最快方法是什么?

回答by PleaseStand

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"));

回答by Mottie

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)时对符号进行转义。

回答by Léa Gris

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,'');
}

回答by shinnyx

回答by Philip

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

回答by Matti Lehtinen

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.

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