JavaScript/replace:修订间差异
来自康健生活
创建页面,内容为“== 字符串变量 == {{leftrightflex|<syntaxhighlight lang="javascript"> const foo = 'abc'; let bar = 'abcdefgh'; eval("bar = bar.replace(/" + foo + "/gi, '+')"); <…” |
小 文字替换 -“{{leftrightflex|”替换为“{{Double-columns|” |
||
| (未显示同一用户的5个中间版本) | |||
| 第1行: | 第1行: | ||
== 字符串变量 == | == 字符串变量 == | ||
{{ | === eval === | ||
{{Double-columns|<syntaxhighlight lang="javascript"> | |||
const foo = 'abc'; | const foo = 'abc'; | ||
let bar = 'abcdefgh'; | let bar = 'abcdefgh'; | ||
eval(" | eval("bar.replace(/" + foo + "/gi, '+')"); | ||
</syntaxhighlight>|{{consoleout|<pre> | </syntaxhighlight>|{{consoleout|<pre> | ||
'+defgh' | '+defgh' | ||
</pre>}}}} | |||
=== RegExp === | |||
{{Double-columns|<syntaxhighlight lang="javascript"> | |||
const foo = 'abc'; | |||
let bar = 'abcdefgh'; | |||
bar.replace(new RegExp(foo, 'gi'), '+'); | |||
bar.replace(new RegExp('(' + foo + ')', 'gi'), '$1');</syntaxhighlight>|{{consoleout|<pre> | |||
'+defgh' | |||
'abcdefgh' | |||
</pre>}}}} | |||
=== arguments === | |||
{{Double-columns|<syntaxhighlight lang="javascript"> | |||
const foo = 'abc'; | |||
let bar = '-----abcdefghabc======='; | |||
bar.replace(new RegExp(foo, 'gi'), function() { | |||
console.log(arguments); | |||
});</syntaxhighlight>|{{consoleout|<pre> | |||
Arguments(3) ['abc', 5, '-----abcdefghabc=======', callee: ƒ, Symbol(Symbol.iterator): ƒ] | |||
Arguments(3) ['abc', 13, '-----abcdefghabc=======', callee: ƒ, Symbol(Symbol.iterator): ƒ] | |||
'-----undefineddefghundefined=======' | |||
</pre>}}}} | |||
替换内容。 | |||
{{Double-columns|<syntaxhighlight lang="javascript"> | |||
const foo = 'abckangjiandefghkangjianijk'; | |||
const bar = 'kangjian'; | |||
const baz = foo.replace( | |||
new RegExp(bar, 'gi'), | |||
function(targetKey, targetIndex, content) { | |||
return '<span>' + targetKey +'</span>'; | |||
}); | |||
console.log(baz);</syntaxhighlight>|{{consoleout|<pre> | |||
abc<span>kangjian</span>defgh<span>kangjian</span>ijk | |||
</pre>}}}} | </pre>}}}} | ||