zoukankan      html  css  js  c++  java
  • javascript替换字符

    不用多言,这种技术被广泛应用于表单验证,语法高亮和危险字符过滤中。一段话如果很长,如果不想像下面那样替换,我们得想些办法了。

    01.str = str.
    02.    replace( /&(?!#?\w+;)/g , '&').
    03.    replace( /"([^"]*)"/g   , '“$1”'   ).
    04.    replace( /</g           , '<'  ).
    05.    replace( />/g           , '>' ).
    06.    replace( /…/g           , '…' ).
    07.    replace( /“/g           , '“'  ).
    08.    replace( /”/g           , '”'  ).
    09.    replace( /‘/g           , '‘'  ).
    10.    replace( /’/g           , '’'  ).
    11.    replace( /—/g           , '—' ).
    12.    replace( /–/g           , '–'  );

    上面这个还算短了,我看过一些论坛的JS代码,在把Wind Code转换成HTML时,那真是疯子似的写上二三十行。其实我们大可以把这些匹配模式与替换后的字符放到一个哈希中,然后一口气替换掉。

    01.var hash = {
    02.    '<' : '<' ,
    03.    '>' : '>',
    04.    '…' : '…',
    05.    '“' : '“' ,
    06.    '”' : '”' ,
    07.    '‘' : '‘' ,
    08.    '’' : '’' ,
    09.    '—' : '—',
    10.    '–' : '–'
    11.};
    12. 
    13.str = str.
    14.    replace( /&(?!#?\w+;)/g , '&' ).
    15.    replace( /"([^"]*)"/g   , '“$1”'  ).
    16.    replace( /[<>…“”‘’—–]/g , function ( $0 ) {
    17.        return hash[ $0 ];
    18.    });

    但这个缺陷也很明显,如哈希的键必须是简单的普通字符串,不能是复杂正则,这就是我们不得不分开的原因。replace在老一点的浏览器不是支持function的。为此,我们只好放弃上面最后那个replace方式,替换方统一为普通字符串。

    01.String.prototype.multiReplace = function ( hash ) {
    02.    var str = this, key;
    03.    for ( key in hash ) {
    04.        if ( Object.prototype.hasOwnProperty.call( hash, key ) ) {
    05.            str = str.replace( new RegExp( key, 'g' ), hash[ key ] );
    06.        }
    07.    }
    08.    return str;
    09.};

    Object.prototype.hasOwnProperty.call( hash, key )是用来过滤继承自原型的方法与属性的。这样一来,使用就简单了:

    01.str = str.multiReplace({
    02.    '&(?!#?\\w+;)' : '&',
    03.    '"([^"]*)"'    : '“$1”',
    04.    '<'            : '<',
    05.    '>'            : '>',
    06.    '…'            : '…',
    07.    '“'            : '“' ,
    08.    '”'            : '”' ,
    09.    '‘'            : '‘' ,
    10.    '’'            : '’' ,
    11.    '—'            : '—' ,
    12.    '–'            : '–'
    13.});

    转:
    http://www.cnblogs.com/rubylouvre/archive/2009/10/12/1581094.html
  • 相关阅读:
    Azkaban的使用
    Azkaban安装
    Kafka 启动失败,报错Corrupt index found以及org.apache.kafka.common.protocol.types.SchemaException: Error reading field 'version': java.nio.BufferUnderflowException
    Kafka 消费者设置分区策略及原理
    Kafka利用Java API自定义生产者,消费者,拦截器,分区器等组件
    zookeeper群起总是有那么几个节点起不来的问题解决
    flume 启动agent报No appenders could be found for logger的解决
    Flume 的监控方式
    Flume 自定义 组件
    Source r1 has been removed due to an error during configuration java.lang.IllegalArgumentException: Required parameter bind must exist and may not be null & 端口无法连接
  • 原文地址:https://www.cnblogs.com/smallfa/p/1581504.html
Copyright © 2011-2022 走看看