0

I am trying to create a script to replace all my double quote texts to be insert inside brackets.

Eg: Input : This "is" a "text". Output : This [is] a [text].

I have tried to fetch all the text elements and using regex replace and print the bracekts.

But it is not working as expected for nested elements.

This is my code sample

HTML

 <p>this "is" a "text" 
   <small>this is "small" text</small>
 </p>
 <h1>"this" is "another"</h1>

Javascript

$(document).ready(function(){
        $('p, h1, h2, h3, h4, h5, div, span, small, b, strong, li').each(function(){

                var re = /([^"]*"[^"]*)"/gm; 
                var str = $(this).text();
                var subst = '$1»'; 
                var result = str.replace(re, subst);
                var resultOdd = result.replace(/"/g, '«');
                $(this).text(resultOdd);
            
        });


        

    })

This is the fiddle for the same.

Can anyone please help me?

Community
  • 1
  • 1
hakkim
  • 666
  • 15
  • 36
  • 1
    `.replace(/"([^"]*)"/g, "[$1]");` – ASDFGerte Mar 05 '20 at 08:56
  • 1
    In question heading you asked about replacing angle brackets, in example you have shown square brackes. What exact replacement you are looking for? – Bhushan Kawadkar Mar 05 '20 at 08:56
  • do you need escapings? could this happenen : "text text\" excaped teext\" text"? If yes, it would be apain to do it with regex, better use other tools – Superluminal Mar 05 '20 at 08:58
  • The regex is only part of the problem. Your much bigger issue is working with text Nodes and recursively looping through nested elements. – Rory McCrossan Mar 05 '20 at 09:00
  • @RoryMcCrossan Exactly... The above code will not work properly for nested elements. – hakkim Mar 05 '20 at 09:24
  • [Parsing HTML with regex is a hard job](https://stackoverflow.com/a/4234491/372239) HTML and regex are not good friends. Use a parser, it is simpler, faster and much more maintainable. – Toto Mar 05 '20 at 12:44

0 Answers0