Max Pain
Max Pain

Reputation: 1237

delete specific part of a string and add another at the end

I have this span on my website with these values.

<span>1,4,4,7,5,9,10</span>

I want to use jquery to delete the "1," (or what ever the first number is) from the beginning of the string and add ",12" at the end (or any other number instead of 12) so it would look like this:

<span>4,4,7,5,9,10,12</span>

How can I do this with jquery or java script ?

Upvotes: 1

Views: 57

Answers (4)

the system
the system

Reputation: 9336

Using DOM API, you can do this:

var tn = span.firstChild;

tn.deleteData(0, tn.data.indexOf(",") + 1);
tn.data += ",12";

http://jsfiddle.net/KMzau/


Or like this:

var tn = span.firstChild;

tn.data = tn.data.slice(tn.data.indexOf(",") + 1) + ",12";

Upvotes: 1

Greg
Greg

Reputation: 3568

You can use split or regular expressions with string.replace

Here's how to use split:

var arr = '1,4,4,7,5,9,10'.split(',');
arr.shift();
arr.push('12');
var result = arr.join(',');

Or with regular expressions (not a very readable one I concede):

'1,4,4,7,5,9,10'.replace(/^\d+,(.*)$/, '$1,12')

Upvotes: 2

Ram
Ram

Reputation: 144709

$('span').text(function(i, t) {
   return t.replace(/\d+,/, '') + ',12';
})

http://jsfiddle.net/dnkEV/

Upvotes: 2

Samuel Liew
Samuel Liew

Reputation: 79073

<span id="myText">1,4,4,7,5,9,10</span>

JS:

var text = $('#myText').html().split(',').slice(1);
text.push('12');
$('#myText').html(text.join(','));

http://jsfiddle.net/samliew/RD6W8/7/

Upvotes: 2

Related Questions