2

How dose i convert below code to javascript regex?

$regex = "~(?i)<[^>]*>(*SKIP)(*F)|[a-z][a-z ]+~";
$replace = '<span class="text=arial">\0</span>';
$replaced = preg_replace($regex,$replace,$original);

Found her

I have tried to follow the link to the demo and use their converter to convert it to JavaScript and now I have this which does not work:

/<[^>]*>(*SKIP)(*F)|[a-z][a-z ]+/gmi

I can not find a substitute for the (*SKIP)(*F) part and I´m not that good at regex.

Could someone please point me in the right direction?

Thanks

Community
  • 1
  • 1
Lasse
  • 575
  • 3
  • 14

2 Answers2

2

If the tags are properly closed then you may free to use a positive lookahead assertion.

([a-z][a-z ]+)(?=[^<>]*<)

DEMO

> string.replace(/([a-z][a-z ]+)(?=[^<>]*<)/gmi, '<span class="text=arial">$1</span>')
'<a href="http://domain.com/path" target="_blank"><span class="text=arial">GSPd </span>役に立つツール: スキル意欲マトリクス</a>'
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
1

If you want to keep the exact same behaviour as the regex in PHP, then you can use a function with the replace to do it:

var text = '<a href="http://domain.com/path" target="_blank">GSPd 役に立つツール: スキル意欲マトリクス</a>';
text = text.replace(/<[^>]*>|([a-z][a-z ]+)/gi, function (m, s) {
    if (s !== undefined) {
        return '<span class="text=arial">' + s + '</span>';
    } else {
        return m;
    }
});

If there is a submatch I have called s here, then return it wrapped in span tags, and if not, return the matched part as is.

Jerry
  • 70,495
  • 13
  • 100
  • 144