user1765862
user1765862

Reputation: 14145

recognize element content and modify dynamically using jquery

I'm injecting text into page using jquery like this

$("#myDiv").text(someWebServiceResponse.Data);

this returned data is in most cases numbers divided with commas but in some cases can be string as a title which is followed with numbers

Returned data case without title

1,2,3,4,89,11

Returned data case with title

MyTitle 1,2,3,4,89,11

Returned data case with title

MyTitle2 1,2,35,4,89,14

Those title and number values are dynamic ofcourse.

How can I recognize if returned data contains title (maybe using typeofstring) and modify this returned string with title +
and than numbers in next line

Upvotes: 0

Views: 48

Answers (3)

Umesh Sehta
Umesh Sehta

Reputation: 10683

try this:-

var isTitle=function(txt){
  var first=txt.substr(0,txt.indexOf(',')); 
  return !$.isNumeric(first);
}
 //here how to use
alert(isTitle('1,2,3,4,89,11'));
alert(isTitle('MyTitle 1,2,3,4,89,11'));

Demo

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074266

With your quoted examples, just find the last space if any and insert the plus sign:

var lastSpace = yourString.lastIndexOf(' ');
if (lastSpace != -1) {
    yourString = yourString.substring(0, lastSpace) + " +" + yourString.substring(lastSpace);
}

Live Example:

test("1,2,3,4,89,11");
test("MyTitle 1,2,3,4,89,11");
test("MyTitle2 1,2,35,4,89,14");

function test(yourString) {
  var lastSpace = yourString.lastIndexOf(' ');
  if (lastSpace != -1) {
    yourString = yourString.substring(0, lastSpace) + " +" + yourString.substring(lastSpace);
  }
  snippet.log(yourString);
}
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

Upvotes: 1

David Votrubec
David Votrubec

Reputation: 4156

Given that the numbers are divided only by , and not by space, you can easily test if the string contains empty space.

Like this

function containsTitle(input) {
    return input.indexOf(' ') > 0;
}

...
if (containsTitle(someWebServiceResponse.Data)) {
   //TODO: split for 2 lines or whatever you need
}

Upvotes: 1

Related Questions