स्ट्रिंग के रूप में रेगेक्स बनाने के लिए, आपको JavaScript's RegExp
object का उपयोग करना होगा।
इसके अलावा, आप एक से अधिक बार मिलान/प्रतिस्थापित करना चाह सकते हैं। उस स्थिति में, the g
(global match) flag जोड़ें। यहाँ एक उदाहरण है:
हर स्ट्रिंग, एक वैध regex है, हालांकि:
var stringToGoIntoTheRegex = "abc";
var regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");
// at this point, the line above is the same as: var regex = /#abc#/g;
var input = "Hello this is #abc# some #abc# stuff.";
var output = input.replace(regex, "!!");
alert(output); // Hello this is !! some !! stuff.
JSFiddle demo here.
सामान्य स्थिति में, regex के रूप में उपयोग करने से पहले स्ट्रिंग से बच: (
या [
जैसे कुछ विशिष्ट पात्र हैं। इस समस्या को हल करने के लिए, इसे रीगेक्स में बदलने से पहले स्ट्रिंग से बचें। उस के लिए एक उपयोगिता समारोह नीचे दिए नमूने में चला जाता है:
function escapeRegExp(stringToGoIntoTheRegex) {
return stringToGoIntoTheRegex.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
var stringToGoIntoTheRegex = escapeRegExp("abc"); // this is the only change from above
var regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");
// at this point, the line above is the same as: var regex = /#abc#/g;
var input = "Hello this is #abc# some #abc# stuff.";
var output = input.replace(regex, "!!");
alert(output); // Hello this is !! some !! stuff.
JSFiddle demo here.
प्रश्न में विशिष्ट मामले के लिए, नोटिस there is no s
(dotall) flag/modifier in JavaScript। जहां यह उपलब्ध है, यह आमतौर पर न्यूलाइन से मेल खाने के लिए डॉट (.
) को मजबूर करता है।यहाँ अपने मामले के लिए एक संभव समाधान है:
var str = $("#div").html();
var regexExpression ="(?!(?:[^<]+>|[^>]+<\\/a>))\\b(" + value + ")\\b";
var regex = new RegExp(regexExpression, "i");
$("#div").html(str.replace(regex, "<a href='#" + value +"'>" + value + "</a>"));
सूचना मैं "<a href='#" + value +"'>"
के अंत में एक लापता '
गयी।
See demo fiddle here। आप this solution using the "g" modifier को भी आजमा सकते हैं।
'value' एक चर है? – Dogbert