0

I have <br> inserted into a string using some logic in typescript. I wanted to remove the <br> at the begining and end of the string. Others should remain as it. What is the best way to achieve?

I achieved it using mystring.substring(mystring.indexOf('<br>'),mystring.lastIndexOf('<br>'))

Want to know if its the optimum way of doing this.

Its a little more complicated.. Should replace all the
in the starting of the string and ending of the string.

<br><br>hello<br>user<br><br><br> should return hello<br>user
Janier
  • 3,982
  • 9
  • 43
  • 96
  • 2
    What have you tried? Where did it go wrong? I'd expect a regular expression like `mystring.replace(/^
    |
    $/g,'')` should work. However you ***must*** also read [*RegEx match open tags except XHTML self-contained tags*](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags). Also see [*regexp101.com*](https://regex101.com).
    – RobG Sep 26 '17 at 22:47
  • I added what i wrote.Can you plz explain this? – Janier Sep 26 '17 at 22:48
  • @jocket mmm your code would break if `mystring` does not end with a `
    `, because you'd end up remove whatever comes after the last `
    `
    – WindowsMaker Sep 26 '17 at 22:49

1 Answers1

1

To do exactly that, you can use this (confirmed locally),

mystring.replace(/(^(<br>)+)|((<br>)+$)/g, '')

See this for more info. Hope it helps.

amal
  • 3,140
  • 1
  • 13
  • 20
  • 1
    There is no need for the replace function, `''` is sufficient, more compatible and likely very much faster. – RobG Sep 27 '17 at 05:48
  • yeah makes sense, I was initially skeptical of it to work only for all the matches within if provided as a replacement function. Should've tried the string type too. Thanks for pointing it out. – amal Sep 27 '17 at 10:37