PDA

View Full Version : wildcard in JavaScript


Dr. Web
09-13-2001, 06:00 PM
I am doing a search and replace function in javascript. I want to use a wildcard (similar to the wildcard in SQL) to look for anything 'like' the search expression.

here is a snippet of code....


<html>
<head>
<title>Untitled</title>
<script language=javascript>
function change(){
var entry=document.form1.textEntry.value;
//the regExpObj is the actual pattern for matching//
var modifiedEntry=(entry.replace('<html>', ""));
modifiedEntry=(modifiedEntry.replace('</html>', ""));
modifiedEntry=(modifiedEntry.replace('<head>', ""));
modifiedEntry=(modifiedEntry.replace('</head>', ""));
modifiedEntry=(modifiedEntry.replace('<title>', ""));
modifiedEntry=(modifiedEntry.replace('</title>', ""));
modifiedEntry=(modifiedEntry.replace('<form>', ""));
modifiedEntry=(modifiedEntry.replace('</form>', ""));
modifiedEntry=(modifiedEntry.replace('<body>', ""));
modifiedEntry=(modifiedEntry.replace('</body>', ""));
modifiedEntry=(modifiedEntry.replace('<p>', ""));
modifiedEntry=(modifiedEntry.replace('</p>', ""));
document.form1.textEntryModified.value=modifiedEntry;
}
</script>
</head>
<body>
<form name=form1>
<textarea name=textEntry rows=15 cols=45 onBlur="change();"></textarea><br>
<textarea name=textEntryModified readOnly rows=15 cols=45></textarea>
</form>
</body>
</html>

Jon Hanlon
09-13-2001, 08:37 PM
Just what the Doctor ordered!


function tagMuncher(mainStr,repStr) {
var pattern = "<" + repStr + "\s?.*>" // eg. <span *> where * is wild
var replaceRE = new RegExp(pattern,"gi");
var newStr = mainStr.replace(replaceRE,"")
var pattern = "</" + repStr + ">" // eg. </span>
var replaceRE = new RegExp(pattern,"gi");
newStr = newStr.replace(replaceRE,"")
return newStr;
}

document.form1.textEntry.value = tagMuncher(document.form1.textEntry.value,"head")
document.form1.textEntry.value = tagMuncher(document.form1.textEntry.value,"h\\d") // h1 to h6

Dr. Web
09-14-2001, 01:09 PM
Excellent! Thanks again Jon!

Jon Hanlon
11-27-2001, 04:50 PM
I've just noticed that, due to the 'greedy' nature of RE's in Javascript, the script doesn't work 100%.

The problem is when we're looking to munch:
<tag>Some Stuff</tag>
and return:
Some Stuff
due to the greedy nature of JavaScript, instead of matching
<tag>Some Stuff</tag>
it will match
<tag>Some Stuff</tag>

There is a non-greedy switch in Javascript 1.5 (replace "\s?.*>" by "\s?.*?>"), but a more general solution is to swop the order of the replacements.


function tagMuncher(mainStr,repStr) {
var pattern = "</" + repStr + ">" // eg. </span>
var replaceRE = new RegExp(pattern,"gi");
var newStr = mainStr.replace(replaceRE,"")
var pattern = "<" + repStr + "\s?.*>" // eg. <span *> where * is wild
var replaceRE = new RegExp(pattern,"gi");
newStr = newStr.replace(replaceRE,"")
return newStr;
}