2011-11-17 58 views
2

Jquery很新在特定字符之後的元素內的字符串中替換文本?

我試圖去掉特定字符後出現的元素內的字符串中的文本。

我得到這個:

<h3>Lorem ipsum dolor sit amet: consectetur adipisicing</h3>

我需要這樣的:

<h3>Lorem ipsum dolor sit amet</h3> 

我是一個新手,真的希望任何幫助提供。 謝謝!

回答

4

最簡單的方法...

$('h3').text(function(i, text) { 
    return text.split(':')[0]; 
}); 

jsFiddle

...但是如果有子元素,這不會覆蓋你。

這段代碼...

var searchText = function(parentNode, regex, callback) { 

    var childNodes = parentNode.childNodes, 
     node; 

    for (var i = 0, length = childNodes.length; i < length; i++) { 

     node = childNodes[i]; 

     if (node.nodeType == 0) { 

      var tag = node.tagName.toLowerCase(); 

      if (tag == 'script' || tag == 'style') { 
       continue; 
      } 

      searchText(node); 

     } else if (node.nodeType == 3) { 

      while (true) { 
       // Does this node have a match? If not, break and return. 
       if (!regex.test(node.data)) { 
        break; 
       } 

       node.data.replace(regex, function(match) { 

        var args = Array.prototype.slice.call(arguments), 
         offset = args[args.length - 2], 
         newTextNode = node.splitText(offset); 

        callback.apply(window, [node].concat(args)); 
        newTextNode.data = newTextNode.data.substr(match.length); 
        node = newTextNode; 

       }); 
      } 
     } 
    } 
} 

searchText($('h3')[0], /:.*$/, function(node) { 
    $(node).next().remove(); 
}); 

jsFiddle

我改編了一些不使用jQuery庫的代碼。您可以使用jQuery稍微優雅一點(例如children(),each()makeArray()等)。

0

要使用JavaScript分裂功能

var x="abcd:efgh"; 

var mysplit=x.split(":"); 

var firsthalf=mysplit[0]; // = abcd 
var otherhalf=mysplit[1]; // = efgh 
1
//iterate through each `<h3>` tag 
$('h3').each(function (index, value) { 

    //cache the current `<h3>` element and get its text 
    var $this = $(value), 
     text = $this.text(); 

    //check for the existence of a colon 
    if (text.indexOf(':') > 0) { 

     //split the text at the colon 
     text = text.split(':'); 

     //set the text of the current `<h3>` element to the text before the first colon 
     $this.text(text[0]); 
    } 
}); 
+0

輝煌!非常感謝! – LJA

相關問題