简体   繁体   中英

How to replace the value in the data attribute of the HTML element

I have a div which has a data-attribute . I want to replace the characters in the string of the data-attribute .

I'm trying to replace \\r\\n with </br> , but I'm unable to achieve it. How can I do this?

<div class="dataval" data-finid="aljslajlsllsjds\r\nsdksadshdsd\r\ndskdsajdsajdasdk\r\nasdashdashdkasj\r\n">
$('.dataval').attr('data-finid').replace(\\r\n\g,"</br>")

There's a few issues here:

  • Your regex is invalid; it needs to be delimited with /
  • \\n needs to be \\\\n
  • You're not doing anything with the output of your replace() call. To update the value you could provide a function to attr() which returns the updated value.

Try this:

 $('.dataval').attr('data-finid', function(i, id) { return id.replace(/\\\\r\\\\n/g, "</br>"); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="dataval" data-finid="aljslajlsllsjds\\r\\nsdksadshdsd\\r\\ndskdsajdsajdasdk\\r\\nasdashdashdkasj\\r\\n">Foo</div> 

 const finid = $('.dataval').attr('data-finid'); console.log(finid.replace(/\\\\r\\\\n/g, "</br>")); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="dataval" data-finid="aljslajlsllsjds\\r\\nsdksadshdsd\\r\\ndskdsajdsajdasdk\\r\\nasdashdashdkasj\\r\\n"> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM