jQuery替换删除删除两个单词之间用括号

时间:2019-06-21 11:47:53

标签: javascript jquery

我正在尝试删除带有括号的两个单词之间的所有内容。这些词是:{start}{end}

  (function ($) {
    $(document).ready(function(){

    $('.well.save').on('mouseleave touchend', function(){
        // alert('mouseleave touchend');
        var $editor = $(".markItUpEditor");
        var curValue = $editor.val();
        //alert(curValue);

        // check
        var confCheck = curValue.includes("{start}");
        //alert(confCheck);
        if (confCheck == true) {


          var myStr = $editor.val();
          var subStr = myStr.match("{start}(.*){end}");
          alert(subStr[1]);
          //$editor.val(curValue);

        }
    });
  })(jQuery);

上面的代码返回null。

我正在从文本区域获取内容。该文本区域有一个部分,在mouseleave上添加了文本。本节以单词{start}开头,以单词{end}结尾,现在我想删除两个单词之间以及单词之间的所有内容,以便在下一次鼠标离开时可以重新添加更新的信息。

jQuery版本来自本地Joomla 3。 文本区域包含以下内容:

There is some text in the message!


[confidential]
{start}

Site URL: 
Site Username: 
Site Password: 

FTP URL: 
FTP Username: 
FTP Password: 

Optional Information: 

{end}
[/confidential]```

3 个答案:

答案 0 :(得分:2)

您的文本区域内容也可能包含换行符,因此给定的正则表达式在我看来不起作用。 将捕获{start}和{end}之间的所有内容的正则表达式为:

/{start}([\s\S]*){end}/gm

https://regex101.com/r/AystH8/1

要删除两个关键字之间的所有内容(包括它们),请使用以下内容:

//If your string is in the variable val;
val = "hi, my name is {start}\n \n gibberish and wrong \ncontent {end} prime hit!";
val = val.replace(/{start}([\s\S]*){end}/gm, "");
console.log(val); // output would be : hi, my name is prime hit!

我希望这能回答您的问题。

答案 1 :(得分:1)

有了字符串后,代码如下- 您的最终编辑给了我提示您有多行字符串。这是修复它的代码

https://regex101.com/r/4MYLO3/3

在-MULTILINE之间移动

var re = /{start}([\S\s]*?){end}/gm 

var str = $(".editor").val()
var newStr = str.replace(re,"");
console.log(newStr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<textarea class="editor" rows="10">There is some text in the message!
    [confidential]
    {start}
    
    Site URL: 
    Site Username: 
    Site Password: 
    
    FTP URL: 
    FTP Username: 
    FTP Password: 
    
    Optional Information: 
    {end}
    [/confidential]</textarea>

从两者之间复制

var re = /{start}([\S\s]*?){end}/gm 

var str = $(".editor").val()
var newStr = str.match(re);
console.log(newStr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<textarea class="editor" rows="10">There is some text in the message!
    [confidential]
    {start}
    
    Site URL: 
    Site Username: 
    Site Password: 
    
    FTP URL: 
    FTP Username: 
    FTP Password: 
    
    Optional Information: 
    {end}
    [/confidential]</textarea>

答案 2 :(得分:-1)

您的match是错误的。

您正在尝试匹配字符串

sdCheck.match("{start}(.*){end}");

当您需要使用正则表达式时

sdCheck.match(/{start}.*{end}/);