Как перенести группу слов с тегами, Регулярными выражениями Замены JavaScript

Почему бы не использовать Шпаклевку?

6
задан Chris 29 November 2009 в 13:48
поделиться

2 ответа

JavaScript doesn't support lookbehind. This is a shame, as we could have done:

// doesn't work in JavaScript:
/((apple|banana|cherry|orange)\b\s?)+(?<!\s)/gi 

What we can do, however, is to move the white-space to the beginning, and add a negative lookahead (so the catch must not start with a white-space):

/(?!\s)(\s?\b(apple|banana|cherry|orange)\b)+/gi

A slight difference from your code is that I also added \b to the beginning of the pattern, so it wouldn't catch apple from Snapple.

4
ответ дан 17 December 2019 в 02:30
поделиться

Вы можете поместить функцию в параметр замены как

function (x) {return "" + x.replace (/ \ s + $ /, "") + "< em> ";} вместо $ &

, и вы можете поместить пробел в эту функцию.

"Apple Banana apple cherry, Cherry orange and Oranges Apple, Banana".replace(
/((?:apple|banana|cherry|orange)\b\s?)+/gi,
function(x){
   return "<em>"+x.replace(/\s+$/,"")+"<em>";
})

<em>Apple Banana apple cherry<em>, <em>Cherry orange<em>and Oranges <em>Apple<em>, <em>Banana<em>
2
ответ дан 17 December 2019 в 02:30
поделиться
Другие вопросы по тегам:

Похожие вопросы: