2013-06-22 2 views
0

답변은 매우 간단해야합니다. 그러나 정규 표현식을 처음 사용합니다.정규 표현식을 사용하여 찾기 및 바꾸기

무엇 난 그냥 찾기 및 바꾸기되고 싶지 :

예를 : iti$%#[email protected]#ombina#$tion.43of//.45simp5./l7e5andsp75e$%cial23$#of%charecters

위의 문장에서 단어 "of"를 "in"로 바꿉니다

나는 이것을 시도했지만 결과를 얻지 못했습니다. 제발 도와주세요.

string="iti$%#[email protected]#ombina#$tion.43of//.45simp5./l7e5andsp75e$%cial23$#of%charecters"; 
var string2=string.replace("/(\w*\W*)of(\w*\W*)/g","$1in$2"); 
console.warn(string2); 

답변

2

왜 단순하지 않습니까? var replaced = yourString.replace(/of/g, 'in');?

+0

감사합니다. + 1 @light 스타일 –

+1

"단어"를 대체하지 않습니다. 완전한 단어가 아닐 때 "와"도 일치합니다. –

0

정규식은 문자열이 아닌 JavaScript의 리터럴 또는 개체입니다.

그래서 :

/(\w*\W*)of(\w*\W*)/g 

나 :

new Regexp("(\\w*\\W*)of(\\w*\\W*)","g"); 
4

regex literal (따옴표) 사용 단어 경계 수정 (\b을 필요 $1 사용하지 않고 $2합니다) :

var string2 = string.replace(/\bof\b/g, "in"); 
+0

+1 내 끝에서. –

1

정규식을 사용하지 않고 전 세계로 대체하십시오.

function replaceMulti(myword, word, replacement) { 
    return myword.split(word).join(replacement); 
} 

var inputString = 'iti$%#[email protected]#ombina#$tion.43of//.45simp5./l7e5andsp75e$%cial23$#of%charecters'; 

var outputString = replaceMulti(inputString, 'of', 'in'); 
+0

이것은 자바가 아닙니다 –

+0

또한, 이것은 하스켈이 아닙니다. – Alp

+0

이것은 "단어"를 대체하지 않습니다. 완전한 단어가 아닐 때 "또한"와 일치하기 때문입니다. – Xotic750

0

이렇게하면?

str.replace("of","in"); 
+2

이것은 하나의 사건 만 대체합니다. 모두 –

+0

이 또한 "단어"를 대체하지 않습니다. 이는 완전한 단어가 아닐 때 "of"와 일치하기 때문입니다. – Xotic750

관련 문제