使用特殊字符时,Javascript替换函数没有按预期工作



我正在尝试在文件中使用新的元数据更新一个div标签,我正在使用替换函数来完成这项工作,但没有按预期工作,它在中间添加垃圾标签。

我正在尝试下面的代码。

let str = `<div data-bind="style:{'background-color':typeof(CalEventBgColor)!=='undefined'? CalEventBgColor:''},css:typeof(CalEventType)!=='undefined'? 'event '+ CalEventType:'event',attr:{ title:dynamicTitle ,id: CalEventId+'$'+$parentContext.$index()+'$'+$index()+$parents[1].componentid}" role="button" tabindex="0">
</div>`;
let oldVal = `<div data-bind="style:{'background-color':typeof(CalEventBgColor)!=='undefined'? CalEventBgColor:''},css:typeof(CalEventType)!=='undefined'? 'event '+ CalEventType:'event',attr:{ title:dynamicTitle ,id: CalEventId+'$'+$parentContext.$index()+'$'+$index()+$parents[1].componentid}" role="button" tabindex="0">`;
let newVal =`<div :class="[[typeof(CalEventType)!=='undefined'? 'event '+ CalEventType:'event']]" :title="[[dynamicTitle]]" :id="[[CalEventId+'$'+$parentContext.$index()+'$'+$index()+$parents[1].componentid]]" :style="[[{ 'background-color':typeof(CalEventBgColor)!=='undefined'? CalEventBgColor:''}]]" role="button" tabindex="0">`;
console.log(str.replace(oldVal,newVal));

基本上,如果你看到:id属性被垃圾字符破坏,请让我知道我们是否可以为此做些什么。

这是因为$用于替换子字符串:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#description

你只需要在每一个美元前再加一个美元符号。字符串CalEventId+'$'+$parentContext.$index()+'$'+$index()应该是这样的CalEventId+'$$'+$$parentContext.$$index()+'$$'+$index()

最新更新