我在编写的一些代码中正在做一些类似的事情
txt = txt.replaceAll('n','').replaceAll('<b>','[bold]').replaceAll('</b>','[/bold]')
.replaceAll('<strong>','[bold]').replaceAll('</strong>','[/bold]')....
其中 replaceAll 是一个 String.prototype 扩展。 这很有效,但我想知道 -
以这种方式链接太多方法有什么缺点吗? 使用在"oner"中完成工作的正则表达式会更好吗? 如果是这样,正则表达式会是什么样子?(我对正则表达式不是很擅长)
这
很好。正则表达式替代方案也非常简单,您基本上只需要使用交替并确保转义需要转义的内容:实时示例 |实时源码
var replacements = {
'n': '',
'<b>': '[bold]'
'</b>': '[/bold]',
'<strong>': '[bold]',
'</strong>': '[/bold]'
// ...
};
txt = txt.replace(/n|<b>|</b>|<strong>|</strong>/g, function(m) {
return m in replacements ? replacements[m] : m;
});
将它们链接在一起是可以的。但不要把它们都放在一行上。如果重新格式化代码,则更容易阅读:
txt = txt
.replaceAll( 'n', '' )
.replaceAll( '<b>', '[bold]' )
.replaceAll( '</b>', '[/bold]' )
.replaceAll( '<strong>', '[bold]' )
.replaceAll( '</strong>', '[/bold]' );
同样的风格在jQuery链中很有用:
$('<div>Test</div>')
.css({ fontSize: '16px' })
.attr({ title: 'Test' })
.appendTo( 'body' );