내가 만들고 싶다 '는' 스트라이드리우스 플라치알레 () 메서드를 사용하여 JavaScript 와 I& # 39 m, regex 약간만이라도 가장 간결한 길일 수도 있다고. 하지만, 제가 can& # 39, t 알아낼 수 있는 regex 변수로 통과하는 방법. 내가 할 수 있는 모든 인스턴스는 이미 대체할 것 '이' 을 (를) ',' a" " b" ",.
"ABABAB".replace(/B/g, "A");
하지만 이 같은 일이 I want to do.
String.prototype.replaceAll = function(replaceThis, withThis) {
this.replace(/replaceThis/g, withThis);
};
하지만 이 텍스트 ',' 에서는 재장착합니다 " replaceThis" 분명히, 이 변수는 .so 어떻게 내 지나갈 수 있는 regex 구체화하십시오?
Regex '/ / g' 구문을 사용하는 대신 새 [정규 표현식] (https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Regular_Expressions) 개체를 구성할 수 있습니다.
var replace = "regex";
var re = new RegExp(replace,"g");
Regex 이렇게 동적으로 객체를 생성할 수 있습니다. 그런 일을 할 것이다.
"mystring".replace(re, "newstring");
에릭 벤델린 언급한 대로, 이 같은 일이 할 수 있습니다.
str1 = "pattern"
var re = new RegExp(str1, "g");
"pattern matching .".replace(re, "regex");
이렇게 하면, 정규 표현식 매칭 ." " ','. 하지만, '는' " .", str1 실패합니다. # 39 you&; d ',' 결과, 패턴 매칭 regex" " 작성되지는 수 있는 ',' 하지만, 이 기간 중 " regex" it& # 39, ll 선반가공 아웃하려면 수 있습니다.
regexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregex
',' 이 (가) 에 있지만, 이 때문에 " ." 문자열으로 regexp 구성자를 it& # 39 의 여전히 모든 문자, 즉, 모든 문자를 받아들여지고 정규식이 줄 바꿈 비사양 마무리라뇨 구체화하십시오. 이를 위해 이 같은 기능을 할 수도 있습니다.
RegExp.quote = function(str) {
return str.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
};
그럼 할 수 있다.
str1 = "."
var re = new RegExp(RegExp.quote(str1), "g");
"pattern matching .".replace(re, "regex");
패턴 매칭 regex" " 중에서, ','.
이:
var txt=new RegExp(pattern,attributes);
이 것과 같습니다.
var txt=/pattern/attributes;
지켜보리니 <, http://www.w3schools.com/jsref/jsref_obj_regexp.asp>.
모든 항목을 afaq 스케쳐내 ('g'), 경계, 활용할 수 있도록 대소문자 무시 ('i'), t # 39 라는 단어 안에 다른 isn& ('\b').
re = new RegExp(`\\b${replaceThis}\\b`, 'gi');
예:
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.
운영까지도 정규식이 구축하기 위해 적절한 소루투리온 동적으로 사용할 수 있는 새로운 정규 표현식 (string) '이' 구성자를. , 구성자를 위해 치료를 위해 특수 문자 그대로 저들이요 이스케이프입니다 합니다 There is 내장현 기능을 jQuery UI 자동완성입니다 위젯 '$ 불렀으매 드위지오토콤프레트리스카페러그렉':
>. [.] 내장현 활용할 수 있습니다. >. '$ 드위지오토콤프레트리스카페러그렉' 기능을. # 39 단일 문자열을 ll 시행하십시오 it&. >. 그 결과 모두 안전한 userdic. 인수와 이스케이프입니다 regex 문자 >. 패스를 '새 정규 표현식 ()'.
Jquery UI 를 사용하는 경우 해당 기능을 사용할 수 있습니다, 또는 복제본에 정의를 소스에서:
function escapeRegex( value ) {
return value.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" );
}
그리고 이를 사용하여 다음과 같습니다.
"[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]"
String.prototype.replaceAll = function(a, b) {
return this.replace(new RegExp(a.replace(/([.?*+^$[\]\\(){}|-])/ig, "\\$1"), 'ig'), b)
}
테스트 it like:
var whatever = 'Some [b]random[/b] text in a [b]sentence.[/b]'
console.log(whatever.replaceAll("[", "<").replaceAll("]", ">"))
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;
};
그리고 커피스크립트 버전니다 스티븐 Penny& # 39 의 응답, 이후 이것은 # 2 는 그냥 커피 경우 구글 레술t.번 javascript 를 많이유 문자 재거됨.;)
baz = "foo"
filter = new RegExp(baz + "d")
"food fight".match(filter)[0] // food
그리고 제 특정 사건
robot.name=hubot
filter = new RegExp(robot.name)
if msg.match.input.match(filter)
console.log "True!"
내 충족하기 위해 필요한 변수를 삽입하려면 / 앨리어스가 정규식이 붙여넣습니다 / 기능, 이것이 내가 지었지.
oldre = /xx\(""\)/;
function newre(e){
return RegExp(e.toString().replace(/\//g,"").replace(/xx/g, yy), "g")
};
String.prototype.replaceAll = this.replace(newre(oldre), "withThis");
여기서 & # 39 oldre& # 39;; 내가 바라는 건 것은 원래의 변수를 삽입하려면, 정규 표현식
[1]: # 488133 https://stackoverflow.com/questions/487509/passing-variable-to-a-regexp-in-javascript/488133
항상 flfile. 'indexOf' 반복적으로 수 있습니다.
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);
};
이 싫어하겠어 무한 루프로 들어갈 때 교체품 map_layer 한국팀을 응원했다.
솔루션 여기 있습니다.
이 중 어떤 난 구현했습니까 전환하여 가치를 창출할 수 있는 텍스트 필드 바꾸려는 is the one 은 다른 with" 교체 및 "; 텍스트 필드) 에서 정규 표현식 기능을 변수를 설정하고, 가치 창출 텍스트 필드 변수로 더 복귀시킴. 저의 경우는 Jquery 를 사용하고, 또한 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));
});
이 코드는 켜있을 온 클릭 한 번으로 이 경우, 함수 호출 할 수 있습니다.
이제 변수가 복귀시킴 함수은 전달할 수 있습니다.
아무도 내게 선택해제합니다 이러한 문제의 답을 했다. 난 결국 http://support. http://burnignorance.com/php-programming-tips/how-to-use-a-variable-in-replace-function-of-javascript/ http://support. 좋은 것이다.
단순 그 답을 찾을 수 있습니다.
var search_term = new RegExp(search_term, "g");
text = text.replace(search_term, replace_term);
예를 들면 다음과 같습니다.
<! - begin 스니핏: js 숨기십시오: 거짓값 콘솔: 진정한 바벨. > 거짓값 -;
$("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>
끝 - < 스니핏 >;!