简体   繁体   English

在JavaScript中转义特殊字符

[英]Escaping special characters in JavaScript

I need a method in JavaScript to escape all characters which are not ( az / AZ / 0-9 / - / _ ) 我需要JavaScript中的方法来转义所有不是(az / AZ / 0-9 /-/ _)的字符

If the character is ø it should be replaced with oe, if it's å then replaced with aa, and more.... if characters are not on the list, they should be replaced with an underscore. 如果字符为ø,则应将其替换为oe,如果将其替换为å,则应将其替换为aa,等等。...如果字符不在列表中,则应将其替换为下划线。

If there are 2 underscores in a row ( __ ) they should be replaced with a single underscore. 如果连续有两个下划线(__),则应将其替换为单个下划线。

I need this done in JavaScript and/or PHP. 我需要在JavaScript和/或PHP中完成此操作。

String.prototype.slugify = function(){
    return this.replace('ø','oe').replace('å','aa').replace(/\W/gi,'_').replace(/_+/g,'_');
}
var x = 'sdfkjshødfjsåkdhf#@$%#$Tdkfsdfxzhfjkasd23hj4rlsdf9';
x.slugify();

Add as many rules as you'd like following the .replace('search','replace') pattern. 按照.replace('search','replace')模式添加尽可能多的规则。 Make sure that you finish it with .replace(/\\W/gi,'_').replace(/_+/,'_') , which converts . 确保使用.replace(/\\W/gi,'_').replace(/_+/,'_')转换。 Also ensure you serve it up in UTF-8 to accommodate the special characters like ø. 另外,还要确保以UTF-8格式提供它,以容纳诸如ø这样的特殊字符。

An alternate version, suggested by Strager: Strager建议的替代版本:

String.prototype.slugify = function(){
    var replacements = {
        'ø': 'oe',
        'å': 'aa'
    }
    var ret = this;
    for(key in replacements) ret = ret.replace(key, replacements[key]);
    return ret.replace(/\W/gi,'_').replace(/_+/g,'_');
}

This version is certainly more flexible and maintainable. 这个版本肯定更加灵活和可维护。 I'd use this one, though I'm keeping the previous iteration for posterity. 我会用这个,尽管我保留后一个迭代。 Great idea, Strager! 好主意,斯特拉格!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM