Jak używać zmiennej w wyrażeniu regularnym?
Chciałbym stworzyć metodę String.replaceAll()
w JavaScript i myślę, że użycie regex byłoby najbardziej zwięzłym sposobem na to. Jednak nie mogę dowiedzieć się, jak przekazać zmienną do wyrażenia regularnego. Mogę to zrobić już teraz, co zastąpi wszystkie instancje "B"
na "A"
.
"ABABAB".replace(/B/g, "A");
Ale ja chcę zrobić coś takiego:
String.prototype.replaceAll = function(replaceThis, withThis) {
this.replace(/replaceThis/g, withThis);
};
Ale oczywiście zastąpi to tylko tekst "replaceThis"
... więc jak przekazać tę zmienną do mojego ciągu regex?
20 answers
Zamiast używać składni /regex/g
, możesz zbudować nowy obiekt RegExp :
var replace = "regex";
var re = new RegExp(replace,"g");
W ten sposób można dynamicznie tworzyć obiekty regex. Wtedy zrobisz:
"mystring".replace(re, "newstring");
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-17 09:53:26
Jak wspomniał Eric Wendelin, możesz zrobić coś takiego:
str1 = "pattern"
var re = new RegExp(str1, "g");
"pattern matching .".replace(re, "regex");
Daje to "regex matching ."
. Jednak nie powiedzie się, jeśli str1 jest "."
. Spodziewałbyś się, że wynik będzie "pattern matching regex"
, zastępując kropkę "regex"
, ale okaże się, że tak...
regexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregex
Dzieje się tak dlatego, że chociaż {[5] } jest łańcuchem znaków, w konstruktorze RegExp jest on nadal interpretowany jako wyrażenie regularne, oznaczające każdy znak w łańcuchu. W tym celu następujące funkcja może być przydatna:
RegExp.quote = function(str) {
return str.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
};
Wtedy możesz zrobić:
str1 = "."
var re = new RegExp(RegExp.quote(str1), "g");
"pattern matching .".replace(re, "regex");
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-06-19 08:15:44
"ABABAB".replace(/B/g, "A");
Jak zawsze: nie używaj regex, chyba że musisz. W przypadku prostego zastąpienia ciągiem, idiom jest następujący:
'ABABAB'.split('B').join('A')
Więc nie musisz się martwić o kwestie cytowania wymienione w odpowiedzi Gracenotes.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-30 11:45:13
Jeśli chcesz uzyskać wszystkie zdarzenia (g
), Bądź niewrażliwy na wielkość liter (i
) i używaj granic, aby nie było to słowo w innym słowie (\\b
):
re = new RegExp(`\\b${replaceThis}\\b`, 'gi');
Przykład:
let inputString = "I'm John, or johnny, but I prefer john.";
let replaceThis = "John";
let re = new RegExp(`\\b${replaceThis}\\b`, 'gi');
console.log(inputString.replace(re, "Jack")); // I'm Jack, or johnny, but I prefer Jack.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-13 02:52:17
Dla wszystkich, którzy chcą używać zmiennej z metodą match , to zadziałało dla mnie
var alpha = 'fig';
'food fight'.match(alpha + 'ht')[0]; // fight
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-09 17:48:28
To:
var txt=new RegExp(pattern,attributes);
Jest równoważne:
var txt=/pattern/attributes;
Zobacz http://www.w3schools.com/jsref/jsref_obj_regexp.asp .
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-01-30 00:19:19
this.replace( new RegExp( replaceThis, 'g' ), withThis );
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-01-16 16:22:43
Chcesz zbudować wyrażenie regularne dynamicznie i w tym celu właściwym rozwiązaniem jest użycie konstruktora new RegExp(string)
. Aby konstruktor traktował znaki specjalne dosłownie, musisz od nich uciec. Istnieje wbudowana funkcja w jQuery UI autocomplete widget o nazwie $.ui.autocomplete.escapeRegex
:
[...] można skorzystać z wbudowanego
$.ui.autocomplete.escapeRegex
funkcja. Wystarczy jeden sznurek argument i escape wszystkie znaki regex, dzięki czemu wynik bezpieczny do pass tonew RegExp()
.
Jeśli używasz jQuery UI możesz użyć tej funkcji lub skopiować jej definicję ze źródła :
function escapeRegex( value ) {
return value.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" );
}
I używaj go tak:
"[z-a][z-a][z-a]".replace(new RegExp(escapeRegex("[z-a]"), "g"), "[a-z]");
// escapeRegex("[z-a]") -> "\[z\-a\]"
// new RegExp(escapeRegex("[z-a]"), "g") -> /\[z\-a\]/g
// end result -> "[a-z][a-z][a-z]"
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-08-21 13:33:48
String.prototype.replaceAll = function (replaceThis, withThis) {
var re = new RegExp(replaceThis,"g");
return this.replace(re, withThis);
};
var aa = "abab54..aba".replaceAll("\\.", "v");
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-02-01 09:28:54
String.prototype.replaceAll = function(a, b) {
return this.replace(new RegExp(a.replace(/([.?*+^$[\]\\(){}|-])/ig, "\\$1"), 'ig'), b)
}
Przetestuj to tak:
var whatever = 'Some [b]random[/b] text in a [b]sentence.[/b]'
console.log(whatever.replaceAll("[", "<").replaceAll("]", ">"))
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-08-20 12:35:29
Aby zaspokoić moją potrzebę Wstawienia zmiennej / aliasu / funkcji do wyrażenia regularnego, oto co wymyśliłem:
oldre = /xx\(""\)/;
function newre(e){
return RegExp(e.toString().replace(/\//g,"").replace(/xx/g, yy), "g")
};
String.prototype.replaceAll = this.replace(newre(oldre), "withThis");
Gdzie 'oldre' jest oryginalnym wyrażeniem regularnym, które chcę wstawić zmienną, 'xx' jest symbolem zastępczym dla tej zmiennej / aliasu / funkcji, a' yy ' jest rzeczywistą nazwą zmiennej, aliasem lub funkcją.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-06-05 04:38:14
I wersja coffeescript odpowiedzi Stevena Penny, ponieważ jest to # 2 wynik google....nawet jeśli kawa jest po prostu javascript z wielu znaków usunięte...;)
baz = "foo"
filter = new RegExp(baz + "d")
"food fight".match(filter)[0] // food
I w moim szczególnym przypadku
robot.name=hubot
filter = new RegExp(robot.name)
if msg.match.input.match(filter)
console.log "True!"
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-29 15:49:09
Oto kolejna implementacja zamiennika:
String.prototype.replaceAll = function (stringToFind, stringToReplace) {
if ( stringToFind == stringToReplace) return this;
var temp = this;
var index = temp.indexOf(stringToFind);
while (index != -1) {
temp = temp.replace(stringToFind, stringToReplace);
index = temp.indexOf(stringToFind);
}
return temp;
};
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-05-08 10:30:36
Podczas gdy możesz tworzyć dynamicznie tworzone wyrażenia regularne (jak w innych odpowiedziach na to pytanie), powtórzę mój komentarz z podobnego posta: Forma funkcjonalna String.replace () jest niezwykle przydatne i w wielu przypadkach zmniejsza zapotrzebowanie na dynamicznie tworzone Obiekty RegExp. (które są rodzajem bólu, ponieważ musisz wyrazić dane wejściowe do konstruktora RegExp jako ciąg znaków, a nie używać ukośników/ [a-z]+ / format dosłowny regexp)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:10:26
Możesz użyć tego, jeśli $1 nie działa z Tobą
var pattern = new RegExp("amman","i");
"abc Amman efg".replace(pattern,"<b>"+"abc Amman efg".match(pattern)[0]+"</b>");
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-06-13 11:13:55
Ta funkcja samo wywołująca będzie iterować nad replacerItems używając indeksu i zmieniać replacerItems[index] globalnie na łańcuchu przy każdym przejściu.
const replacerItems = ["a", "b", "c"];
function replacer(str, index){
const item = replacerItems[index];
const regex = new RegExp(`[${item}]`, "g");
const newStr = str.replace(regex, "z");
if (index < replacerItems.length - 1) {
return replacer(newStr, index + 1);
}
return newStr;
}
// console.log(replacer('abcdefg', 0)) will output 'zzzdefg'
Zawsze możesz używać indexOf
wielokrotnie:
String.prototype.replaceAll = function(substring, replacement) {
var result = '';
var lastIndex = 0;
while(true) {
var index = this.indexOf(substring, lastIndex);
if(index === -1) break;
result += this.substring(lastIndex, index) + replacement;
lastIndex = index + substring.length;
}
return result + this.substring(lastIndex);
};
To nie wchodzi w nieskończoną pętlę, gdy zamiennik zawiera dopasowanie.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-08-16 19:53:34
Twoje rozwiązanie jest tutaj:
Przekazuje zmienną do wyrażenia regularnego.
Ten, który zaimplementowałem, polega na pobraniu wartości z pola tekstowego, które jest tym, które chcesz zastąpić, a innym jest pole tekstowe "replace with", pobranie wartości z pola tekstowego w zmiennej i ustawienie zmiennej na funkcję RegExp, aby dalej zastępować. W moim przypadku używam Jquery, można to również zrobić tylko JavaScript zbyt.
Kod JavaScript:
var replace =document.getElementById("replace}"); // getting a value from a text field with I want to replace
var replace_with = document.getElementById("with"); //Getting the value from another text fields with which I want to replace another string.
var sRegExInput = new RegExp(replace, "g");
$("body").children().each(function() {
$(this).html($(this).html().replace(sRegExInput,replace_with));
});
Ten kod czy onclick Zdarzenie przycisku, można umieścić to w funkcji do wywołania.
Więc teraz możesz przekazać zmienną w funkcji replace.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-12 06:56:26
Żadna z tych odpowiedzi nie była dla mnie jasna. W końcu znalazłem dobre wyjaśnienie na http://burnignorance.com/php-programming-tips/how-to-use-a-variable-in-replace-function-of-javascript/
Prosta odpowiedź brzmi:
var search_term = new RegExp(search_term, "g");
text = text.replace(search_term, replace_term);
Na przykład:
$("button").click(function() {
Find_and_replace("Lorem", "Chocolate");
Find_and_replace("ipsum", "ice-cream");
});
function Find_and_replace(search_term, replace_term) {
text = $("textbox").html();
var search_term = new RegExp(search_term, "g");
text = text.replace(search_term, replace_term);
$("textbox").html(text);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textbox>
Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum
</textbox>
<button>Click me</button>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-10-18 18:37:43
Dla wielokrotnego zastępowania bez wyrażeń regularnych wybrałem następujące:
let str = "I am a cat man. I like cats";
let find = "cat";
let replace = "dog";
// Count how many occurrences there are of the string to find
// inside the str to be examined.
let findCount = str.split(find).length - 1;
let loopCount = 0;
while (loopCount < findCount)
{
str = str.replace(find, replace);
loopCount = loopCount + 1;
}
console.log(str);
// I am a dog man. I like dogs
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-11-24 01:52:17