0

This question is an epilogue of the great question Mix Razor and Javascript code where I learn about this syntax:

@if (foo)
{
    // C# code
    <text>
    // JS Code
    </text>
}

It worked well, until today, when I used a JS regex inside the <text></text> :

$('#bar').html(boo.replace(/<br([\/ ]*)>/g, "\r\n"));

Which throw a yellow page telling me that there was an issue with br( which can't be analyzed.

Is there an inline way to deal with it?

Community
  • 1
  • 1
Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142
  • Did you try escaping it? `/\
    /`
    – Mike Cluck Oct 21 '16 at 14:24
  • @MikeC same result :/ – Thomas Ayoub Oct 21 '16 at 14:27
  • You might try the `@()` syntax suggested in the answer to [Using javascript regex containing '@' in razor](http://stackoverflow.com/a/34580370/215552). Additionally, there's a great answer on [Using Razor within JavaScript](http://stackoverflow.com/a/4599403/215552) that might help. It might be nice to update your title too to reflect that you've got the angle brackets. Otherwise, with the title being just like a ton of other questions, it tends to look like a duplicate. – Heretic Monkey Oct 21 '16 at 14:52

1 Answers1

1

(replaced my previous answer)

I tested this code in an MVC View, and it works:

<div id="bar" style="border: 1px solid black">
    Dummy content (should be replaced)
</div>
<script type="text/javascript">
    var boo = "<span>hello<br />world</span>";
    var symbolLT = "<";
    @if (1 == 1)
    {
        // C# code
        <text>
        var regex = new RegExp(symbolLT + "br([\/ ]*)>", "g");
        $('#bar').html(boo.replace(regex, "\r\n"));
        </text>
    }
</script>

The trick is to isolate the "<" character from the <text></text> block, and to use new RegExp(). Perhaps a bit less readable than a normal inline expression, but it surely works.

Or you can simply create the regex earlier on the page, so outside of the <text></text> block, and then use it inside.

Peter B
  • 22,460
  • 5
  • 32
  • 69