简体   繁体   中英

Javascript: Remove last occurence of comma in span tag

I want to append object keys to span tag with class result and separate them with comma. But I can't remove last occurence of comma in text.

Result: <span class="result"></span>

Javascript:

for (key in obj) {
    $(".result").append(key + ",");
}

So, for example, instead of 1,2,3, it must be 1,2,3

You may use the "join" method in order to combine array elements with separators between them like so:

var sample = ["1", "2", "3"];
console.log(sample.join(","));
//outputs: 1,2,3

It does not work on object properties though, so you have to use Object.keys() in order to convert your object into an array of its properties (supported in most browsers).

$(".result").append(Object.keys(obj).join(","));

Do it like this

var str = "1,2,3,"
str = str.slice(0,-1)
console.log(str) //"1,2,3"

For your SPAN I did this.

$('.result').text($('.result').text().slice(0,-1))

Try solution in fiddle join() function of array comes in real handy

// if array
var ele = ["1", "2", "3"]
$(".result").append(ele.join(","));


// if object 
var ele1 = { "a": 1, "b" :2, "c" : 3}
var value = $.map(ele1, function(k, v) { return k;}).join(",")
$(".result1").append(value)

It will replace all trailing ','.

 var str = "1,2,3,"
 str.replace(/,+$/g,"")

DEMO

You can also use the array methods:

var test = "a,b,c,,,";
var test1 = test.split(",");
while (!test1[test1.length-1]) {
  test1.pop();
}
console.log(test1);
test = test1.join(",");
console.log(test);

I would do, instead:

var results = (Object.keys(obj)).join(",");
$(".result").append(results);

Far more simpler. More efficient ;) If you do an append in a loop, the page will be redrawn every time you add a key. That's slow. Plus, with Object.keys(obj) ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys ) you get an array with all the keys of the object, and you only need to join all elements in a string, separating it with a comma. So more concise, no?

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