使用jQuery replaceWith()将所选文本替换为输入文本

时间:2014-02-19 02:18:20

标签: javascript jquery

我希望让用户能够从正文中输入一个短语,然后将该文本替换为用户想要的任何内容。我相信.replaceWith()在这里最好,但我不完全确定如何实现它。

这是输入区域的HTML。

<h2>Replace</h2>
<table>
    <tr>
        <td>Original:</td>
        <td>
            <input id="original" type="text" />
        </td>
    </tr>
    <tr>
        <td>New Text:</td>
        <td>
            <input id="newtext" type="text" />
        </td>
    </tr>
    <tr>
        <td colspan="2">
            <input id="replace" type="button" name="save" value="Replace" />
        </td>
    </tr>
</table>
</div>

我希望用户能够从#text(正文)输入单词或短语,然后输入输入的新文本部分,他们想要替换原始文本的文本用。

我遇到一个棘手问题的一件事是考虑到用户可以输入“原始”文本中的任何单词或短语,并将“原始”文本替换为他们想要的任何内容。

我想像

$("table").click(function(){
    $("#text").replaceWith("anything the user wants");
});

谢谢!

所有的

<!DOCTYPE html> 
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("#red").click(function(){
    $("#text").css("color","red");
  });
  $("#blue").click(function(){
    $("#text").css("color","blue");
});
  $("#green").click(function(){
    $("#text").css("color","green");
});

  $("#times_new_roman").click(function(){
    $("#text").css("font-family","'Times New Roman'");
}); 
  $("#courier").click(function(){
    $("#text").css("font-family","courier");
}); 

  $("#comic_sans").click(function(){
    $("#text").css("font-family","'Comic Sans MS'");
}); 
  $("#arial").click(function(){
    $("#text").css("font-family","Arial");
}); 
    $('input[name="decoration"]').change(function(){
        if ($(this).val() == 'bold'){
            if ($(this).is(':checked')) $("#text").css('font-weight', "bold");
            else $("#text").css('font-weight', "normal");
        }
        else if ($(this).val() == 'italic'){
            if ($(this).is(':checked')) $("#text").css('font-style', "italic");
            else $("#text").css('font-style', "normal");
        }

    });
      $('input[name="font"]').bind('keypress', function (event) {
    var regex = new RegExp("[0-9]");
    var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
    if (!regex.test(key)) {
       event.preventDefault();
       return false;
    }
});

$("#up").click(function () {
    var currentSize = $("#text").css("font-size");
    currentSize = currentSize.replace(/[^\d.]/g, "");
    currentSize++;
    if(currentSize < 10 || currentSize > 80){
        alert("Font-size between 10 and 80 only!");
    }
    else {
        $("#text").css("font-size", "" + currentSize + "px");
    }
});

$("#down").click(function () {
    var currentSize = $("#text").css("font-size");
    currentSize = currentSize.replace(/[^\d.]/g, "");
    currentSize--;
    if(currentSize < 10 || currentSize > 80){
        alert("Font-size between 10 and 80 only!");
    }
    else {
        $("#text").css("font-size", "" + currentSize + "px");
    }

});

$('input[name="font"]').on("keyup change", function () {
    var newSize = $(this).val();
    if(newSize < 10 || newSize > 80){
        alert("Font-size between 10 and 80 only!");
    }
    else {
        $("#text").css("font-size", "" + newSize + "px");
    }
});

    });

</script>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>INFO 2300 - HW1</title> 
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script type="text/javascript" src="script.js"></script>
    <link rel="stylesheet" type="text/css" href="stylesheet.css" title="StyleSheet" /> 
</head>

<body>
    <div id="wrapper">
        <h1>Super Cool Javascript Text Editor</h1>
        <form id="controlForm" class="controls" action="index.php" method="post" onsubmit="return false;">
            <div id="color">
                <h2 class="test2">Font Color</h2>
                <label for="red">Red</label> 
                <input type="radio" name="color" value="Red" id="red" /><br />
                <label for="blue">Blue</label> 
                <input type="radio" name="color" value="Blue" id="blue" /><br />
                <label for="green">Green</label> 
                <input type="radio" name="color" value="Green" id="green" /><br />
            </div>

            <div>
                <h2>Font Family</h2>
                <!-- Giving specific names, then generic ones, is useful for font families
                    because not everyone has every font. -->
                <label for="courier">Courier</label> 
                <input type="radio" name="family" value="courier,monospace" id="courier" /><br />
                <label for="times_new_roman">Times New Roman</label> 
                <input type="radio" name="family" value="times new roman,serif" id="times_new_roman" /><br />
                <label for="arial">Arial</label> 
                <input type="radio" name="family" value="arial,sans-serif" id="arial" /><br />
                <label for="comic_sans">Comic Sans MS</label> 
                <input type="radio" name="family" value="comic sans ms, sans-serif" id="comic_sans" /><br />
            </div>
            <div id="font">
                <h2>Font Size</h2>
                <input name="font" type="text" value="15"/>px
                <br /><span id="sizeWarning"></span>
            <div>
                </div>
                <h2>Text Decoration</h2>
                <label for="bold">Bold</label> 
                <input type="checkbox" name="decoration" value="bold" id="bold" /><br />

                <!-- Added for italic -->
                <label for="italic">Italic</label> 
                <input type="checkbox" name="decoration" value="italic" id="italic" /><br />
            </div>

            <div>
                <h2>Search Features [Already Implemented]</h2>
                <input id="search" type="text" name="search"/>
            </div>

            <div>
                <h2>Replace</h2>
                <table>
                <tr><td>Original: </td><td><input id="original" type="text" /></td></tr>
                <tr><td>New Text: </td><td><input id="newtext" type="text" /></td></tr>
                <tr><td colspan="2"><input id="replace" type="button" name="save" value="Replace" /></td></tr>
                </table>
            </div>

        </form>


        <form id="myform" class="test" action="saveFile.php" method="post">
        <div id="saveResult" class="saveResult">
            <input name="hiddentext" type="hidden" />
            <input name="settings" type="hidden" />
            <input name="savebutton" type="submit" value="Save file" />
        </div>
        </form>

        <div id="text">
        <?php
            //reads in the file
            $file = file("lorem.txt");
            foreach($file as $line){
                echo "<p>".$line."</p>";
            }
        ?>

        </div>
    </div>
</body>
</html>

3 个答案:

答案 0 :(得分:1)

你的意思是

if (!RegExp.escape) {
    RegExp.escape = function (s) {
        return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
    };
}
jQuery(function () {
    $('#replace').click(function () {
        var text = $('#original').val();
        if (text) {
            var regex = new RegExp(RegExp.escape(text), 'g');
            $('h2').text(function (i, text) {
                return text.replace(regex, $('#newtext').val())
            })
        }
    })
})

演示:Fiddle

您可以使用简单的正则表达式替换目标

中的搜索字符串

答案 1 :(得分:0)

你可以使用              $('#text')。text('你想要的任何东西');

答案 2 :(得分:0)

如果我理解正确,你想要做的就是替换div#text中的单个单词,其中每行文本都包含在<p></p>标签内。 (这是故意的吗?如果没有,请在评论时告诉我,我将在一个P标签中添加如何保留所有答案的答案。)

回答这个问题的步骤是:

  1. 获取元素的文本
  2. 搜索并替换
  3. 在元素#text
  4. 上设置新文本

    这样做:

    function replaceTextAtDiv(){
        var div_text = $("#text").text();
        var textToReplace = $("#original").val();
        var newText = $("#newtext").val();
        div_text.replace(textToReplace, newText);
        $("#text").text(div_text);
    
        /* OR - In One Line
    
        /$("#text").text($("#text").text().replace($("#original").val(), $("#newtext").val()));*/
    }
    

    <强>建议 将所有文本放在<p></p>包装器中。这样做:

    <?php
        //reads in the file
        $file = file("lorem.txt");
        $string = "";
        foreach($file as $line){
            $string = $string . "\n" . $line; //Take away [  . "\n" ] if it generates 2 line breaks.
        }
        echo "<p>".$string."</p>";
    ?>