简体   繁体   English

使用jquery在动态更改文本时拆分字符串

[英]using jquery to split strings on dynamically changing text

I am trying to use jQuery to split a text string and remove/hide part of the string. 我正在尝试使用jQuery拆分文本字符串并删除/隐藏字符串的一部分。 This is all part of a single span class that is dynamically generated. 这是动态生成的单个跨度类的全部。

<span>Item in transit from Centerville since 05/14/2018<span>

The problem is the "since 04/12/2018" is always different. 问题是“自2018年12月12日起”始终是不同的。 The date always changes. 日期总是改变的。 I want the element to look like this: 我希望元素看起来像这样:

<span>Item in transit from Centerville</span>

Is there a way to do this with jQuery? 有没有办法做到这一点的jQuery? One constant seems to be the 'since' part, which always precedes the dynamically generated date. 一个常量似乎是“自”部分,该部分始终在动态生成的日期之前。 Can that be used to split the string and achieve my desired result? 可以用来分割字符串并达到我想要的结果吗?

Thanks in advance. 提前致谢。

If every one of these strings has "since {some date}" at the end, then you could just do: 如果这些字符串中的每个字符串末尾都带有“自{some date}开始”,那么您可以这样做:

The HTML part: HTML部分:

<span id="string">Item in transit from Centerville since 1/1/2018</span>

With jQuery: 使用jQuery:

let string = $("#string").text();
//'let string = document.getElementById("string").innerText' if you want to just pure javascript
let desiredString = string.split(" since");[0]

That will give you "Item in transit from Centerville". 这将为您提供“从Centerville运送中的物品”。 Just know that it completely discards everything after it, so you'd have to do something different if you actually want to have a hide/show behavior. 只是知道它完全丢弃了所有内容,因此,如果您实际上想要具有隐藏/显示行为,则必须做一些不同的事情。

Example: 例:

 let string = document.getElementById("string").innerText; let desiredText = string.split(" since")[0]; document.getElementById("changed").innerText = desiredText; 
 <p>Original</p> <span id="string">Item in transit from Centerville since 1/1/2018</span> <p>Changed</p> <span id="changed"></span> 

  1. Since the date is always at last use split() with space to make an array of words then use pop() to get the last element which is the date. 由于日期总是最后一次,请使用split()和空格创建单词数组,然后使用pop()获取最后一个元素,即日期。

 var $text = $('span').text(); console.log($text.split(' ').pop()) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <span>Item in transit from Centerville since 05/14/2018</span> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM