Question

So I've been trying to do $(document).match(/regexp/); and I keep getting "undefined is not a function"

When I do $(document)html().match(/regexp/); TypeError: Cannot read property 'match' of undefined

The regexp I'm using is /^[~{.*?}~]$/ All I want to do is search the html document for [~{ any kind of input }~] so that I can then replace it with the right code using jQuery. Essentially, I'll be creating my own templating engine. The current ones, either don't do what I need, or are over bloated.

<body>

    [~{ header }~]


    <p>This is the home page</p>


    [~{ footer }~]

</body>

So I guess I wasn't clear, what I need to do is find text within "[~{" and "}~]". Then after placing it within a variable and determining what to do with it, I'll then find the entire expression again, but this time I'll replace it with other content.

So

[~{ header }~]

I would find this with match or something, extract the "header" text into a variable. From there I'll have it go through a function. The function will return something to do like retrieve getting an html page and load it. But it'll then have to find the expression again to replace it.

Was it helpful?

Solution

$(document) returns a jQuery object, not a string. You need to call html() to get the HTML contents of the document. You can do:

$('body').html(function(contents) {
    return contents.replace(/regexp/, 'replacement');
});

If you just want to see the match:

var match = $('body').html().match(/regexp/);
console.log(match);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top