在模板中对字符串 replace 时,参数含 '&' 符号不生效
Vue version
latest
Link to minimal reproduction
Steps to reproduce
<script setup>
import { ref, computed } from 'vue'
const msg = ref('Hello & World!')
const ok = computed(() => msg.value.replace(/&/, '&'))
</script>
<template>
<p>{{ msg.replace(/&/, '&') }}</p>
<p>{{ 'Hello & World'.replace(/&/, '&') }}</p>
<p>o{{ msg.replace(/&/, '-') }}</p>
<p>{{ msg.replace(/amp;/, '-') }}</p>
<p>{{ ok }}</p>
</template>
What is expected?
<p>{{ msg.replace(/&/, '&') }}</p>
should be result to:
<p> Hello & World! </p>
What is actually happening?
but this code
<p>{{ msg.replace(/&/, '&') }}</p>
has the following result:
<p> Hello & World! </p>
System Info
No response
Any additional comments?
No response
Vue template follows HTML syntax so &
inside your template is already decoded into &
in your JavaScript code. You can see this from the compiled output:
return (_ctx, _cache) => {
return (_openBlock(), _createElementBlock(_Fragment, null, [
_createElementVNode("p", null, _toDisplayString(msg.value.replace(/&/, '&')), 1 /* TEXT */),
_createElementVNode("p", null, _toDisplayString('Hello & World'.replace(/&/, '&')), 1 /* TEXT */),
_createElementVNode("p", null, "o" + _toDisplayString(msg.value.replace(/&/, '-')), 1 /* TEXT */),
_createElementVNode("p", null, _toDisplayString(msg.value.replace(/amp;/, '-')), 1 /* TEXT */),
_createElementVNode("p", null, _toDisplayString(ok.value), 1 /* TEXT */)
], 64 /* STABLE_FRAGMENT */))
}