Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid regular expression flags error when generating button

I am getting the error

Invalid regular expression flags

From the edit button when I click on it. But HTML output seems to be fine

/* EDIT */ {
    mRender: function (data, type, row) {
        var directlink = '/Products/edit/' + row.ArticleID;
        return "<button type='button' class='btn btn-sm btn-primary' onclick='location.href=" + directlink + "'><i class='fa fa-pencil-square-o'> </i> Edit</button>"

Out come of generated button from JavaScript

<button type="button" class="btn btn-sm btn-primary" onclick="location.href=/Products/edit/11"><i class="fa fa-pencil-square-o"> </i> Edit</button>
like image 437
MVC newbie Avatar asked Aug 24 '26 11:08

MVC newbie


2 Answers

The error is in the code onclick='location.href=" + directlink + "'. Here, location.href is assigned a RegEx(Note that regex literal syntax uses / as delimiters).

Here, /Products/edit/11 is read as Regex /Products/ and edit as regex flags, which are Invalid flags(except i).

To solve this, the value of the URL can simply be wrapped inside quotes. As both single and double quotes are already used, the quotes need to be escaped.

onclick='location.href=\"" + directlink + "\"'

If target environment support EcmaScript 6 template literals, you can use

return `<button ... onclick='location.href="${directlink}'>...</button>`;

As, yo're using jQuery, I'd suggest to use it to create new element and bind events on it.

like image 196
Tushar Avatar answered Aug 27 '26 02:08

Tushar


Looking at the generated button, you are missing the quotes for the string in the assignment on the onclick handler

So instead of this:

onclick="location.href=/Products/edit/11"

It should be this:

onclick="location.href='/Products/edit/11'"

Since literal regex's uses the / javascript assumed it was a regex, hence the error

like image 23
JSelser Avatar answered Aug 27 '26 03:08

JSelser



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!