In a Javascript function I need to replace all forward slashes not part of an HTML tag with /
.
Is there any way using a regular expression to find all forward slashes between a >
and a <
?
In a Javascript function I need to replace all forward slashes not part of an HTML tag with /
.
Is there any way using a regular expression to find all forward slashes between a >
and a <
?
Not exactly, but if you're in this kind of a fix, I guess you'll be happy with a quick-and-dirty solution: Find a /
if the next occurring angle bracket is not a closing angle bracket.
result = subject.replace(/\/(?![^<>]*>)/g, "/");
Of course, this is highly brittle - for example it doesn't care at all about comments, strings etc. (yet, and it would be very difficult to pull this off with regex).
You can test this:
html ='<a href="/sdfsdf/SD/sdfsf">toto/tata</a>';
html = html.replace(/(<[^>]+>)|\//g,
function (match, p1) { return (p1)?match:"/"; });
console.log (html);
The idea is to capture all html tags (and replace by themselves) before trying to match slashes. Then a callback function tests if the first capture group exist and return the full match or the replacement.
You can improve the safety of this pattern to deal with style and script content, like this:
html = html.replace(/(<s(tyle|cript)\b[\s\S]*?<\/s\2>|<[^>]+>)|\//gi,
function (match, p1, p2) { return (p1)?match:"/"; });
here is a good example. First hit on google: http://james.padolsey.com/javascript/find-and-replace-text-with-javascript/
The basic idea is to iterate through all the nodes in the DOM and replace text in text nodes. Also, don't replace any text in nodes in script, style, metadata type tags. While you might be able to do this with one big regex, it doesn't make much sense to implement a dom parser in regex when there is one built into every browser.
function findAndReplace(searchText, replacement, searchNode) {
if (!searchText || typeof replacement === 'undefined') {
// Throw error here if you want...
return;
}
var regex = typeof searchText === 'string' ?
new RegExp(searchText, 'g') : searchText,
childNodes = (searchNode || document.body).childNodes,
cnLength = childNodes.length,
excludes = 'html,head,style,title,link,meta,script,object,iframe';
while (cnLength--) {
var currentNode = childNodes[cnLength];
if (currentNode.nodeType === 1 &&
(excludes + ',').indexOf(currentNode.nodeName.toLowerCase() + ',') === -1) {
arguments.callee(searchText, replacement, currentNode);
}
if (currentNode.nodeType !== 3 || !regex.test(currentNode.data) ) {
continue;
}
var parent = currentNode.parentNode,
frag = (function(){
var html = currentNode.data.replace(regex, replacement),
wrap = document.createElement('div'),
frag = document.createDocumentFragment();
wrap.innerHTML = html;
while (wrap.firstChild) {
frag.appendChild(wrap.firstChild);
}
return frag;
})();
parent.insertBefore(frag, currentNode);
parent.removeChild(currentNode);
}
}
Then use it
findAndReplace('\\/', '/');