使用jquery在两个字符串之间获取字符串

Yus*_*liq 1 jquery attributes image extract src

如果我有这个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>
Run Code Online (Sandbox Code Playgroud)

如何使用jquery我可以提取之间的值[img][/img],并将其设置为变量data-src2=""的内<img>给予元件

<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>
Run Code Online (Sandbox Code Playgroud)

我没有什么给什么我都试过,因为我没有做一个线索如何提取价值之间[img][/img]

但总体来说就是我想要实现,如果它没有任何意义!

Dav*_*mas 9

经过测试并且现在可以正常工作(原始版本没有遍历所有.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);
    });
Run Code Online (Sandbox Code Playgroud)

JS小提琴.


编辑因为我有点无聊,所以把上面变成了更通用的功能:

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 +'"/>');
    });
Run Code Online (Sandbox Code Playgroud)

JS小提琴演示.


在OP的进一步问题后编辑(在下面的评论中):

...函数为每个div添加一个''与class comment-body一起如何只能将代码应用于包含[img] image src的comment-body元素[/ 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+'"/>');
        }
    });
Run Code Online (Sandbox Code Playgroud)

JS小提琴演示.


编辑回应OP的进一步问题(在下面的评论中):

[是]有一种方法可以防止它删除此示例中的文本"这里的随机文本"[?]

是的,你可以.append(),或者.prepend()将图像转换成元素,首先更新的文字后div,在下面的代码我已经删除了[img]...[/img]字符串,离开只是其他文本,插入文本到.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 +'"/>');
        }
    });
Run Code Online (Sandbox Code Playgroud)

JS小提琴演示.


参考文献:

  • 缺少近距离支撑?*什么*缺少近距离...?*咳嗽*编辑*咳嗽*...... (2认同)
  • @Yusaf:大卫的代码运作良好(+1:o)).你只需要使用`tagString`来创建`<img>`元素(如[here](http://jsfiddle.net/dzejkej/kYK7e/14/)). (2认同)
  • 我在帖子的末尾添加了一些参考资料,供大家阅读.可能需要一段时间才能熟悉JavaScript,甚至是jQuery.只要问你有问题(一旦你*尝试*研究它们),当你能够时,开始回答.我现在没有时间看你的小提琴,但我会记得明天,下班后再看.=) (2认同)