无法在jQuery中拆分字符串 [英] unable to split string in jquery

查看:114
本文介绍了无法在jQuery中拆分字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 <table border="0"  class="commentbox">
   <tr>
     <td>
          <div id="comment-f78d0b00-a008-473d-b647-a4a103ee3778"></div>
         <input type="button" class='btnReply' id="reply-f78d0b00-a008-473d-b647-a4a103ee3778" value="Reply"/>

     </td>
 </tr>
</table>

  $(".commentbox .btnReply").live("click", function () {
            //  $(this).hide();
            // i = 1;
            id = $(this).attr("id").split("-")[1]
            alert(id);
            var strDiv = 
             "<input type='text' class='txtCmnt' id='txtReply-" + id + "' /> 
        <input type='button' class='btnSave' value='Save' id='btnSave-" + id + "' /> ";
            $("#comment-" + id).append(strDiv);


        });

我希望f78d0b00-a008-473d-b647-a4a103ee3778在拆分后发出警报 f78d0b00

i want the f78d0b00-a008-473d-b647-a4a103ee3778 to come after split rather alert is giving f78d0b00

我尝试更改id = comment_ f78d0b00-a008-473d-b647-a4a103ee3778并拆分

I have tried to change id = comment_ f78d0b00-a008-473d-b647-a4a103ee3778 and split

id = $(this).attr("id").split("_")[1],but it doesnt work.

已编辑

输入-container-f78d0b00-a008-473d-b647-a4a103ee3778

Input - container-f78d0b00-a008-473d-b647-a4a103ee3778

输出:拆分f78d0b00-a008-473d-b647-a4a103ee3778

Output after split f78d0b00-a008-473d-b647-a4a103ee3778

推荐答案

一种获得最终结果的复杂方法:

A slightly convoluted means of achieving your end-result:

// splits the supplied string by the hyphen '-' character
var string = 'comment-f78d0b00-a008-473d-b647-a4a103ee3778'.split(/-/);
    // removes the zeroeth/first element from the string array
    string.shift();
    // joins the remaining elements from the string back together
var newString = string.join('-');
console.log(newString);​

JS小提琴演示.

已编辑以将以上内容转换为功能:

Edited to turn the above into a function:

function splitString(haystack, needle){
    if (!needle || !haystack){
        return false;
    }
    var string = haystack.split(needle);
    string.shift();
    return string.join(needle);
}

// the first argument is the string you want to work on,
// the second is the character you want to split on
// f is the variable that will hold the new string
var f = splitString('comment-f78d0b00-a008-473d-b647-a4a103ee3778','-');
console.log(f);​

JS Fiddle演示.

参考文献:

这篇关于无法在jQuery中拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆