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

标签 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>

如何使用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>

我没有任何东西可以给出我所尝试的,因为我不知道如何提取 [img] 之间的值和[/img]

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

最佳答案

经过测试,现在可以工作(原始版本没有迭代所有 .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的进一步问题(在下面的评论中):

...the function adds an '' to every div with the class comment-body how can i only have the code applied to comment-body elements that contain [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的进一步问题(在下面的评论中):

[Is] there a way of preventing it from removing the text in this example 'random text here'[?]

是的,在第一次更新 div 的文本后,您可以 .append().prepend() 将图像添加到元素中code>,在下面的代码中,我删除了 [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 +'"/>');
        }
    });

JS Fiddle demo .

<小时/>

引用文献:

关于jquery - 使用jquery获取两个字符串之间的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8378575/

相关文章:

vue.js - Vue点击按钮时改变属性值的方法

javascript - 如何使用 Javascript 从屏幕区域创建图像?

image - 用 Mathematica 中的自定义图像替换像素?

JQuery.Validate 添加带有消息的动态规则

javascript - 使用 *ngIf 作为切换以 Angular 2 显示 div 内容

java - 通过他的属性获取一个元素

c - 这个程序如何运行 C?

javascript - JQuery UI 选项卡 - 动态添加和删除鼠标悬停事件

javascript - 获取 html 并删除 javascript/jquery 上的特定元素

c# - 限制可以使用 C# 自定义属性的位置