简体   繁体   中英

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. 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. 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? 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:

The HTML part:

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

With 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". 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.

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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