который имеет преимущество для работы с другими двигателями регулярных выражений тоже.

от вопрос уже есть ответ здесь:

Как мне сопоставить любой символ в нескольких строках регулярного выражения? 21 ответ

Я люблю регулярные выражения. Тем не менее, я только сейчас столкнулся с невозможностью использоватьs флаг при запуске JavaScript RegExp в браузере. Мне интересно, почему этот флаг не включен? Это было бы действительно полезно.

Я видел, что есть внешняя библиотекаXRegExp что позволяет этоs флаг (и некоторые другие), но мне также любопытно, почему эти дополнительные (и полезные) флаги также не существуют в стандартном JavaScript. Я также не хочу включать еще одну внешнюю библиотеку ...

Вот пример, в котором я пытаюсь решить проблему с обнаружением открывающих / закрывающих тегов для коротких кодов WordPress, которые могут иметь новые строки внутри (или мне нужно вставить новые строки между ними, чтобы улучшить обнаружение).

//
// Let's take some input text, e.g. WordPress shortcodes
//
var exampleText = '[buttongroup class="vertical"][button content="Example 1" class="btn-default"][/button][button class="btn-primary"]Example 2[/button][/buttongroup]'

//
// Now let's say I want to extract the shortcodes and its attributes
// keeping in mind shortcodes can or cannot have closing tags too
//
// Shortcodes which have content between the open/closing tags can contain
// newlines. One of the issues with the flags is that I can't use `s` to make
// the dot character.
//
// When I run this on regex101.com they support the `s` flag (probably with the
// XRegExp library) and everything seems to work well. However when running this
// in the browser I get the "Uncaught SyntaxError: Invalid regular expression
// flags" error.
//
var reGetButtons = /\[button(?:\s+([^\]]+))?\](?:(.*)\[\/button\])?/gims
var reGetButtonGroups = /\[buttongroup(?:\s+([^\]]+))?\](?:(.*)\[\/buttongroup\])?/gims

//
// Some utility methods to extract attributes:
//

// Get an attribute's value
//
// @param string input
// @param string attrName
// @returns string
function getAttrValue (input, attrName) {
  var attrValue = new RegExp(attrName + '=\"([^\"]+)\"', 'g').exec(input)
  return (attrValue ?  window.decodeURIComponent(attrValue[1]) : '')
}

// Get all named shortcode attribute values as an object
//
// @param string input
// @param array shortcodeAttrs
// @returns object
function getAttrsFromString (input, shortcodeAttrs) {
  var output = {}
  for (var index = 0; index < shortcodeAttrs.length; index++) {
    output[shortcodeAttrs[index]] = getAttrValue(input, shortcodeAttrs[index])
  }
  return output
}

//
// Extract all the buttons and get all their attributes and values
//
function replaceButtonShortcodes (input) {
  return input
    //
    // Need this to avoid some tomfoolery.
    // By splitting into newlines I can better detect between open/closing tags,
    // however it goes out the window when newlines are within the
    // open/closing tags.
    //
    // It's possible my RegExps above need some adjustments, but I'm unsure how,
    // or maybe I just need to replace newlines with a special character that I
    // can then swap back with newlines...
    //
    .replace(/\]\[/g, ']\n[')
    // Find and replace the [button] shortcodes
    .replace(reGetButtons, function (all, attr, content) {
      console.log('Detected [button] shortcode!')
      console.log('-- Extracted shortcode components', { all: all, attr: attr, content: content })

      // Built the output button's HTML attributes
      var attrs = getAttrsFromString(attr, ['class','content'])
      console.log('-- Extracted attributes', { attrs: attrs })
      
      // Return the button's HTML
      return '<button class="btn ' + (typeof attrs.class !== 'undefined' ? attrs.class : '') + '">' + (content ? content : attrs.content) + '</button>'
    })
}

//
// Extract all the button groups like above
//
function replaceButtonGroupShortcodes (input) {
  return input
    // Same as above...
    .replace(/\]\[/g, ']\n[')
    // Find and replace the [buttongroup] shortcodes
    .replace(reGetButtonGroups, function (all, attr, content) {
      console.log('Detected [buttongroup] shortcode!')
      console.log('-- Extracted shortcode components', { all: all, attr: attr, content: content })
      
      // Built the output button's HTML attributes
      var attrs = getAttrsFromString(attr, ['class'])
      console.log('-- Extracted attributes', { attrs: attrs })
      
      // Return the button group's HTML
      return '<div class="btn-group ' + (typeof attrs.class !== 'undefined' ? attrs.class : '' ) + '">' + (typeof content !== 'undefined' ? content : '') + '</div>'
    })
}

//
// Do all the extraction on our example text and set within the document's HTML
//
var outputText = replaceButtonShortcodes(exampleText)
outputText = replaceButtonGroupShortcodes(outputText)
document.write(outputText)

С помощьюs Флаг позволил бы мне сделать это легко, однако, поскольку он не поддерживается, я не могу использовать преимущества флага.

Ответы на вопрос(1)

Ваш ответ на вопрос