Home > Mobile >  Javascript replace function is not working as expected with special character
Javascript replace function is not working as expected with special character

Time:04-26

I am trying to update a div tag with new metadata in a file and I am using the replace function to do this job ,but is not working as expected , it is adding junk tag in the middle.

I am trying this below code.

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 : :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));

Basically if you see the :id property it is broken with junk character, please let me know if we can do something for this.

CodePudding user response:

It happens because $ is used to replace substring: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#description

You just have to add one more dollar sign before every dollar. This string CalEventId '$' $parentContext.$index() '$' $index() should look like this CalEventId '$$' $$parentContext.$$index() '$$' $index()

  • Related