【问题标题】:get string between two strings using jquery使用jquery获取两个字符串之间的字符串
【发布时间】:2012-01-12 19:05:40
【问题描述】:

如果我有这个 HTML

<div class="comment-body">
[img]http://topnews.net.nz/images/YouTube-3.jpg[/img] random text here
</div>

<div class="comment-body">
[img]http://blog.brightcove.com/sites/all/uploads/FACEBOOK%20ICON.png[/img] random text here
</div>

如何使用 jquery 提取 [img][/img] 之间的值并将其设置为 &lt;img&gt; 元素中的变量 data-src2="" 给予

<div class="comment-body">
<img src="samesrc" class="commentimg" data-src2="http://topnews.net.nz/images/YouTube-3.jpg"/> random text here
</div>

<div class="comment-body">
<img src="samesrc" class="commentimg" data-src2="http://blog.brightcove.com/sites/all/uploads/FACEBOOK%20ICON.png"/> random text here
</div>

对于我所尝试的东西,我没有什么可提供的,因为我不知道如何提取 [img][/img] 之间的值

但总的来说 THIS 是我想要实现的目标,如果它没有意义的话!

【问题讨论】:

  • 不需要jQuery,只需要一个简单的简正则表达式!
  • 那么,你想要一个 BBCode 解析器?
  • @Rocket 类似的东西是的,它让事情变得更容易!
  • 到目前为止你尝试过什么?请表现出一些努力。另外:stackoverflow.com/questions/1843320/…
  • 我希望我可以为评论点赞 10 次

标签: jquery attributes image extract src


【解决方案1】:

经过测试,现在可以使用(原始版本没有遍历所有 .comment-body 元素,或者正确找到 substring()):

var divString, imgString;
$('.comment-body').each(
    function(){
        divString = $(this).text();
        imgString = divString.substring(divString.indexOf('[img]') + 5,divString.indexOf('[/img]'));
        console.log(imgString);
    });

JS Fiddle.


编辑,因为我有点无聊,所以把上面的变成了一个更通用的函数:

function findStringBetween(elem,bbTagStart,bbTagClose){
    var tag = bbTagStart;

    function impliedEndTag(tag){
        var impliedEnd = tag.replace(tag.substring(0,1),tag.substring(0,1) + '/');
        return impliedEnd;
    }

    var endTag = bbTagClose || impliedEndTag(tag);

    var divString = $(elem).text();
    var tagString = divString.substring(divString.indexOf('[img]') + tag.length,divString.indexOf('[/img'));
    return tagString;
}
$('.comment-body').each(
    function(){
        /* call with two, or three arguments (the third is the optional 'bbTagClose':
            1. elem = this, the DOM node,
            2. '[img]' = whatever bbCode thing you want to use (I'm not sure what's available),
            3. 'bbTagClose' = the end tag of the bbCode, assuming that the end-tag is the same as
                the opening tag, except with a '/' as the second character, the impliedEndTag() function
                will take care of it for you.
        */
        var elemString = findStringBetween(this,'[img]');
        $(this).replaceWith('<img src="' + elemString + '" class="commentimg" data-src2="'+ elemString +'"/>');
    });

JS Fiddle demo.


编辑以下来自 OP 的进一步问题(在 cmets 中,如下):

...该函数向每个带有注释主体类的 div 添加一个 '' 我如何才能只将代码应用于包含 [img]image src here[/img]

的注释主体元素

我添加了一些健全性检查,以确保在未找到定义的标签时函数返回 false:

function findStringBetween(elem,bbTagStart,bbTagClose){
    var tag = bbTagStart;

    function impliedEndTag(tag){
        var impliedEnd = tag.replace(tag.substring(0,1),tag.substring(0,1) + '/');
        return impliedEnd;
    }

    var endTag = bbTagClose || impliedEndTag(tag);
    var divString = $(elem).text().trim(); // added .trim() to remove white-spaces

    if (divString.indexOf(tag) != -1){ // makes sure that the tag is within the string
        var tagString = divString.substring(divString.indexOf('[img]') + tag.length,divString.indexOf('[/img'));
        return tagString;
    }
    else { // if the tag variable is not within the string the function returns false
        return false;
    }
}
$('.comment-body').each(
    function(){
        /* call with two, or three arguments (the third is the optional 'bbTagClose':
            1. elem = this, the DOM node,
            2. '[img]' = whatever bbCode thing you want to use (I'm not sure what's available),
            3. 'bbTagClose' = the end tag of the bbCode, assuming that the end-tag is the same as
                the opening tag, except with a '/' as the second character, the impliedEndTag() function
                will take care of it for you.
        */
       var imgLink = findStringBetween(this,'[img]');
        if (imgLink){ // only if a value is set to the variable imgLink will the following occur
            $(this).replaceWith('<img src="' + imgLink + '" class="commentimg" data-src2="'+ imgLink+'"/>');
        }
    });

JS Fiddle demo.


编辑以回应 OP 的进一步问题(在 cmets 中,如下):

[是否]有办法阻止它删除此示例“此处的随机文本”中的文本[?]

是的,你可以将.append(),或者.prepend()的图片放入元素中,先更新div的文字后,在下面的代码中我已经去掉了[img]...[/img]这个字符串,留下just 其他文本,将该文本插入到 .comment-body 元素中,然后将 img 附加到该元素中,而不是使用 replaceWith()

function findStringBetween(elem,bbTagStart,bbTagClose){
    var tag = bbTagStart;

    function impliedEndTag(tag){
        var impliedEnd = tag.replace(tag.substring(0,1),tag.substring(0,1) + '/');
        return impliedEnd;
    }

    var endTag = bbTagClose || impliedEndTag(tag);
    var divString = $(elem).text().trim();

    if (divString.indexOf(tag) != -1){
        var elemInfo = [];
        elemInfo.imgString = divString.substring(divString.indexOf(tag) + tag.length,divString.indexOf(endTag));
        elemInfo.text = divString.replace(tag + elemInfo.imgString + endTag, '');
        return elemInfo;
    }
    else {
        return false;
    }
}
$('.comment-body').each(
    function(){
        /* call with two, or three arguments (the third is the optional 'bbTagClose':
            1. elem = this, the DOM node,
            2. '[img]' = whatever bbCode thing you want to use (I'm not sure what's available),
            3. 'bbTagClose' = the end tag of the bbCode, assuming that the end-tag is the same as
                the opening tag, except with a '/' as the second character, the impliedEndTag() function
                will take care of it for you.
        */
       var elemInfo = findStringBetween(this,'[img]');
        if (elemInfo.imgString){
            // or .prepend() if you prefer
            $(this).text(elemInfo.text).append('<img src="' + elemInfo.imgString + '" class="commentimg" data-src2="'+ elemInfo.imgString +'"/>');
        }
    });

JS Fiddle demo.


参考资料:

【讨论】:

  • 先生,我不知道您在说什么世界只看到一阵风。
  • @Yusaf:David 的代码运行良好(+1 :o))。您只需要使用tagString 来创建&lt;img&gt; 元素(如here)。
  • 读者注意:如果您的代码经常调用findStringBetween(),请考虑在findStringBetween() 之外定义函数impliedEndTag()。当一个函数包含另一个函数时,每次调用“父”函数时都会创建其“子”函数。所以调用findStringBetween() 100 次意味着impliedEndTag() 被创建了100 次。请参阅 this article
  • 我在文章末尾添加了一些参考资料,供您阅读。熟悉 JavaScript 甚至 jQuery 可能需要一段时间。只需提出您的问题(一旦您尝试研究它们),当您有能力时,开始回答。我现在没时间看你的小提琴,但我会尽量记住明天下班后看。 =)
  • @DavidThomas 干得好,大卫!所有这些参考资料都有不错的额外奖励:)。
【解决方案2】:

大卫·托马斯所写的另一种答案。

实现此代码的另一种方法是使用正则表达式。

// inputText - input text that contains tags
// tagName - name of the tag we want to replace
// tagReplace - replacement for the tag, "$1" will get replaced by content of the tag
function replaceText(inputText, tagName, tagReplace) {
  var regExp = new RegExp('\\[' + tagName+ '\\]([^\\[]*)\\[\/' + tagName + '\\]', 'g');
  return inputText.replace(regExp, tagReplace);
}

$('.comment-body').each(function() {
  var $this = $(this);
  var replacedText = replaceText($this.text(), 'img', '<img src="$1" \/>');
  $this.html(replacedText);
});

此实现还将替换评论中的多个标签。

THIS代码sn-p。

注 1:

在实际环境中实现此代码时,请考虑为 replaceText() 之外的所有已处理标记名称预先创建正则表达式,这样就不会在每次调用 replaceText() 时创建 regExp

注2:

要获得问题更改中的确切输出:

  var replacedText = replaceText($this.text(), 'img', '<img src="$1" \/>');

  var replacedText = replaceText($this.text(), 'img', '<img src="samesrc" class="commentimg" data-src2="$1" \/>');

【讨论】:

  • 你怎么能改变它,让它与我拥有的 YouTube 标签一起工作,因为它们也使用 $1 jsfiddle.net/x7N7S/11
  • @Yusaf:我建议你学习一下并试验一下代码,这样你就可以自己修改它了。如果您仍有问题,请创建一个新问题。仅使用 cmets 讨论具体问题的具体答案,而不用于其他目的。仅供参考:我的答案中的代码会将整个 youtube 链接放到$1。要解决您的问题,您需要修改正则表达式以仅提取 ?watch= 部分而不是 youtube 链接,或者仅在标签之间插入 ?watch=thisPart(更通用的解决方案):请参阅 THIS
  • 谢谢你,我已经尝试了一些东西,但它们没用,我将从现在开始发布失败的链接,对不起。
  • @Yusaf:很高兴为您提供帮助 :)。抱歉,如果这听起来很粗鲁,但是创建一个问题可以帮助其他人更轻松地找到相同的问题,帮助您拥有更好的工具(如代码块、5 分钟以上的编辑能力等)的人,他们可以获得一些额外的代表作为奖励:)。
  • 我已经为我遇到的 [youtube][/youtube] 和 [img][/img] 问题创建了一个解决方案,dzejkej 和 David Thomas,非常感谢你们。
【解决方案3】:

此函数在任何字符串中查找任何给定的 bbcode,如果需要,您可以将其配置为从这些 bbcode 中替换或提取内容作为数组。

//search str 
var search_str = "I love this [img]question.png[/img] Flowers, and [img]answer_1-1.png[/img] you say is that [img]answer_2-1.png[/img] good Point."
//using example
var str = bbcode_search_and_replace($('#search_str').text(),"[img]","[/img]");
$('#search_str').html(str);

function bbcode_search_and_replace(search_str, bb_opening_tag, bb_closing_tag) {
            //search str length
           var sLength = String(search_str).length;
           //bbcode opening tag length
           var fPart_length = String(bb_opening_tag).length;
           //bbcode closing tag length
           var ePart_length = String(bb_closing_tag).length;
           //position index for opening tag 
           var start_idx = 0;
           //position index for closing tag 
           var end_idx = 0; 
           //searching index for opening tag
           var pos_sIdx = 0;
           //position index for closing tag
           var pos_eIdx = 0;
           //var replacement = '[image]';
           var arr = [];
           var idx = 0;           

           //loop
           while(start_idx !== -1) {
               arr[idx] = {};                  

               start_idx = String(search_str).indexOf(bb_opening_tag,pos_sIdx);
               //check for ending
               if(start_idx === -1) {
                   //if exist, last str after closing tag
                   if(idx > 0) arr[idx]['str'] = search_str.substring(pos_sIdx);
                   console.log("arr[idx]['str'] = " + arr[idx]['str']);
                   break;
               }
               //end position index
               pos_eIdx = start_idx + fPart_length;
               end_idx = String(search_str).indexOf(bb_closing_tag,pos_eIdx);                   
               //save str inside bbtags
               arr[idx]['str'] = search_str.substring(pos_sIdx, start_idx);
               console.log("arr[idx]['str'] = " + arr[idx]['str']);
               arr[idx]['src'] =  "<img src = 'img/" + search_str.substring(start_idx + fPart_length, end_idx) + "' />";
               console.log("arr[idx]['src'] = " + arr[idx]['src']);
               arr[idx]['pos_start'] = start_idx + fPart_length;
               arr[idx]['pos_end'] = end_idx;                                

               //Update array and start pos indexes
               idx++;
               pos_sIdx = end_idx + ePart_length;                
          }

           var k = 0;
           var str = "";
           while(k < arr.length) {
               if(arr[k]['src'] === undefined) arr[k]['src'] = "";
               str += arr[k]['str'] + arr[k]['src'];
               k++;
           }

           return str;
        }  

【讨论】:

    【解决方案4】:

    使用JavaScript match()函数,非常好用

    如果你有一个字符串“快速棕色狐狸跳过懒狗。”

    & 你需要介于“quick”和“lazy”之间的文本

    在下面使用

    <script type="text/javascript">
       var myStr = "The quick brown fox jumps over the lazy dog.";
       var subStr = myStr.match("quick(.*)lazy");
       alert(subStr[1]);
    </script>
    

    希望对你有帮助!!

    【讨论】:

      猜你喜欢
      • 2012-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-12
      • 1970-01-01
      相关资源
      最近更新 更多