0

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.

2
  • String manipulation would be a javascript undertaking. Not really a jQuery operation. You could use jQuery to get the string, but manipulating it would be a javascript thing. Commented May 14, 2018 at 22:02
  • Open to resolutions that are pure javascript as well... Commented May 14, 2018 at 22:04

2 Answers 2

1

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>

Sign up to request clarification or add additional context in comments.

1 Comment

let newString = string.split(" since", 1);
0
  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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.