Subscribe on changes!

在模板中对字符串 replace 时,参数含 '&' 符号不生效

avatar
Jul 26th 2023

Vue version

latest

Link to minimal reproduction

https://play.vuejs.org/#eNqNks1OwzAQhF9l8aFppZAceitpJUCVgAMgQOLiS5RsQ9rEtvxTKkV5d9auUoooFTd75xt7du2OXSuVbB2yGctMoWtlwaB1asFF3SqpLXSgcRVDIVvlLJbQw0rLFiIyRVxwUUhhLLSmgrknx9EdNo2EUd6qK3iXuikvosmAyQ1Rw1Hj8QTmC29NtnnjMNGomrzAcRrMaQzRKJqQN0v30SgUbSy2hFmkHUCmFl0Xjjhphr7PUt/MQP5OF/3HKf+85PLEJT/IcyCNYyhl6VFfLGbW0MRWdZWsjRT0Op13ceZnVzeon5StaaKczSAoXsups8+HULPaYTzUiw8sNifqa7PzNc6eNRrUW+TsoNlcV2j38vL1EXe0PoitLF1D9BnxBY1snM+4x26cKCn2ERfS3oc/VovqzSx3FoUZmvJBPdkHnjP6bbdnWv+OO02mwcdFz/ov06/tAw==

Steps to reproduce

<script setup>
import { ref, computed } from 'vue'

const msg = ref('Hello &amp; World!')
const ok = computed(() => msg.value.replace(/&amp;/, '&'))
</script>

<template>
  <p>{{ msg.replace(/&amp;/, '&') }}</p>
  <p>{{ 'Hello &amp; World'.replace(/&amp;/, '&') }}</p>
  <p>o{{ msg.replace(/&amp;/, '-') }}</p>
  <p>{{ msg.replace(/amp;/, '-') }}</p>
  <p>{{ ok }}</p>
</template>
image

What is expected?

<p>{{ msg.replace(/&amp;/, '&') }}</p>

should be result to:

<p> Hello & World! </p>

What is actually happening?

but this code

<p>{{ msg.replace(/&amp;/, '&') }}</p>

has the following result:

<p> Hello &amp; World! </p>

System Info

No response

Any additional comments?

No response

avatar
Jul 26th 2023

Vue template follows HTML syntax so &amp; 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 */))
}