0
var a = '<span class="test">33.3;34.55</span><img src="../../../test.gif" onclick=testThis(''open'')><span class="test">33.3;34.55</span><img src="../../../test.gif" onclick=testThis(''open'')>0.22';

Here, I need to replace dots in all parts of the string except in src and onclick. I have used two for loops to replace these tags and data with a placeholder. And replaced all dot with comma.

'<span class="test">33,3;34,55</span><img src=src_ph onclick=onclick_ph><span class="test">33,3;34,55</span><img src=src_ph onclick=onclick_ph>0,22';

But now I need those tags and data again. For this I have to make use of forloop again. Is there better solution? Thanks

sonam81
  • 157
  • 2
  • 9
  • Can you add your code for the for loop you are using? – Tom Mar 23 '22 at 10:26
  • 4
    Why do you have a string with HTML and `onclick` attributes and are not using the DOM API to manipulate it? How is this string going to be used? Will it be appended into the DOM somewhere? – Sebastian Simon Mar 23 '22 at 10:26
  • 2
    The only way to do this reliably is to use a DOM parser and loop through the text nodes. You might try it with regex (and people may post answers with regex), but **regex cannot be reliably used for this**. HTML is too complex, and is not a regular language, hence not being able to use regular expressions on it reliably. – T.J. Crowder Mar 23 '22 at 10:28
  • @SebastianSimon Yes it will be appended on DOM. – sonam81 Mar 23 '22 at 10:29
  • 1
    @sonam81 See [Parse an HTML string with JS](/q/10585029/4642212) and use the [DOM API](//developer.mozilla.org/en/docs/Web/API/Document_Object_Model) to get all the text nodes. Inline event handlers like `onclick` are [bad practice](/q/11737873/4642212). They’re an [obsolete, cumbersome, and unintuitive](/a/43459991/4642212) way to listen for events. Always [use `addEventListener`](//developer.mozilla.org/en/docs/Learn/JavaScript/Building_blocks/Events#inline_event_handlers_%E2%80%94_dont_use_these) instead. – Sebastian Simon Mar 23 '22 at 10:37
  • This looks to be an X-Y problem - trying to debug code that was unlikely to meet your needs in the first place. Where does the string assigned to `a` come from, is it guaranteed to be valid HTML (it's not in the post, which generates a syntax error), and what are the click handlers supposed to do - for example `onclick_ph>0,22` won't compile, and `testThis(...)` doesn't pass a useful `this` value - need looking at. I would suggest rewording the question to describe what needs to be done, and include the code in details of what you have tried. – traktor Mar 23 '22 at 11:35

0 Answers0