You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用jQuery删除字符串末尾单词并替换指定字符串内容?

Got it, let's tackle your two questions one by one:

1. 替换字符串中的"hello"为其他单词

First, let's look at your original string:

<i class="jstree-icon jstree-checkbox" role="presentation"></i> <i class="jstree-icon jstree-themeicon fa fa-folder-open icon-state-warning icon-lg jstree-themeicon-custom" role="presentation"></i> hello

情况1:处理纯字符串

If you're working directly with the string variable, use JavaScript's native replace() method—super straightforward:

// 原始字符串
const originalStr = '<i class="jstree-icon jstree-checkbox" role="presentation"></i> <i class="jstree-icon jstree-themeicon fa fa-folder-open icon-state-warning icon-lg jstree-themeicon-custom" role="presentation"></i> hello';
// 把"hello"替换成你想要的单词,比如"world"
const updatedStr = originalStr.replace('hello', 'world');

情况2:处理DOM元素中的内容

If this HTML is inside a DOM element (like a <div> or <span>), jQuery makes it easy to update the content in place. Let's say your element has an ID of tree-node:

$('#tree-node').html(function(index, currentHtml) {
  // 替换"hello"为你的目标单词
  return currentHtml.replace('hello', 'your-custom-word');
});
2. 用jQuery删除字符串的最后一个单词

jQuery is great for DOM manipulation, but the core logic to remove the last word relies on string handling (which we can do with native JS, wrapped in jQuery methods). Here's how to do it:

方法:针对DOM元素内容

Let's use the same tree-node element example. We'll grab the content, split it into words, remove the last one, then put it back:

$('#tree-node').html(function(index, currentHtml) {
  // Split the content into an array of words (handles multiple spaces with regex)
  const wordArray = currentHtml.split(/\s+/);
  // Remove the last element from the array (that's the last word)
  wordArray.pop();
  // Join the array back into a string with spaces
  return wordArray.join(' ');
});

纯字符串处理(无DOM)

If you just need to process a string variable (no jQuery required for this part, but it's useful to know):

const myString = 'This is a sample text';
const wordArray = myString.split(/\s+/);
wordArray.pop();
const stringWithoutLastWord = wordArray.join(' ');
// Result: "This is a sample"

Note: Using split(/\s+/) instead of split(' ') ensures we handle cases where there are multiple consecutive spaces (it won't create empty string entries in the array).

内容的提问来源于stack exchange,提问作者Shubham Agarwal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:01:24