开发者

Replace the contents of a div with regex match of string

I'm trying to figure out how to replace the contents of a <div> with the results from a regex .match() statement on a string. This is the code I have so far but I can't get it to work. I want the button to stay on screen but the <div> to reflect the matched word.

<html>
<body>
    <script type="text/javascript">
    function search(){
        var str = "Visit W3Schools";
        var patt1 = /w3schools/i;
        document.write(str.replace(document.getElementById("results"),
                                   (str.match(patt1))));
    }
    </script>
</body开发者_如何转开发>

<div id="results">So this is some text.</div>
<button name="Search" onclick="search()">Click Here</button>
</html>

Any ideas as to why it's not working?


You need to stop the button completing it's default event, which is to submit the page. (Edit: No it's not, its default event is nothing - assumed it was a <submit> :) )

In addition, to get a div from the document basic on it's id attribute, you use document.getElementById('id-of-element') and to set the contents of a div, you use .innerHTML on the element we just got.

// We need to take the event handler as a parameter for the function, let's call it e
function search(e){
    var str = "Visit W3Schools";
    var patt1 = /w3schools/i;
    document.getElementById("results").innerHTML = str.match(patt1)[0];
    // This line stops the default action occurring
    e.preventDefault();
}

Note: we don't need to specify an argument here, e goes in automatically

<button name="Search" onclick="search()">Click Here</button>


Your code is searching for the String "So this is come text." in the String "Visit W3Schools" and replacing it with the array ["W3Schools"], then writing it to the screen. This doesn't make much sense.

Try something like this instead:

function search(){
    var str = "Visit W3Schools";
    var patt1=/w3schools/i;
    document.getElementById("results").innerHTML=(str.match(patt1))[0];
}


document.write will replace the entire page with the passed in parameter. So you just want to update that single DIV, results. So you want to use innerHTML:

function search() {
    var str = "Visit W3Schools";
    var patt1 = /w3schools/i;
    document.getElementById("results").innerHTML = str.match(patt1)[0];
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜