JavaScript/replace:修订间差异
来自康健生活
小 文字替换 -“{{leftrightflex|”替换为“{{Double-columns|” |
|||
| (未显示同一用户的3个中间版本) | |||
| 第1行: | 第1行: | ||
== 字符串变量 == | == 字符串变量 == | ||
=== eval === | === eval === | ||
{{ | {{Double-columns|<syntaxhighlight lang="javascript"> | ||
const foo = 'abc'; | const foo = 'abc'; | ||
let bar = 'abcdefgh'; | let bar = 'abcdefgh'; | ||
| 第9行: | 第9行: | ||
</pre>}}}} | </pre>}}}} | ||
=== RegExp === | === RegExp === | ||
{{ | {{Double-columns|<syntaxhighlight lang="javascript"> | ||
const foo = 'abc'; | const foo = 'abc'; | ||
let bar = 'abcdefgh'; | let bar = 'abcdefgh'; | ||
bar.replace(new RegExp(foo, 'gi'), '+');</syntaxhighlight>|{{consoleout|<pre> | bar.replace(new RegExp(foo, 'gi'), '+'); | ||
bar.replace(new RegExp('(' + foo + ')', 'gi'), '$1');</syntaxhighlight>|{{consoleout|<pre> | |||
'+defgh' | '+defgh' | ||
'abcdefgh' | |||
</pre>}}}} | </pre>}}}} | ||
=== arguments === | === arguments === | ||
{{ | {{Double-columns|<syntaxhighlight lang="javascript"> | ||
const foo = 'abc'; | const foo = 'abc'; | ||
let bar = '-----abcdefghabc======='; | let bar = '-----abcdefghabc======='; | ||
| 第25行: | 第28行: | ||
Arguments(3) ['abc', 13, '-----abcdefghabc=======', callee: ƒ, Symbol(Symbol.iterator): ƒ] | Arguments(3) ['abc', 13, '-----abcdefghabc=======', callee: ƒ, Symbol(Symbol.iterator): ƒ] | ||
'-----undefineddefghundefined=======' | '-----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>}}}} | ||