Get and replace the last number on a string with JavaScript or jQuery

前端 未结 7 1549
挽巷
挽巷 2021-02-14 11:02

If I have the string:

var myStr = \"foo_0_bar_0\";

and I guess we should have a function called getAndIncrementLastNumber(str)

7条回答
  •  难免孤独
    2021-02-14 11:25

    Will the numbers be seperated with some characters? What I understood from you question is your string may look like this 78_asd_0_798_fgssdflh__0_2323 !! If this is the case, first you need to strip out all the characters and underscores in just one go. And then whatever you have stripped out you can either replace with comma or some thing.

    So you will basically have str1: 78_asd_0_798_fgssdflh__0_2323 ; str2: 78,0,0,798,2323.

    str2 need not be a string either you can just save them into a variable array and get the max number and increment it.

    My next question is does that suffice your problem? If you have to replace the largest number with this incremented number then you have to replace the occurence of this number in str1 and replace it with your result.

    Hope this helps. For replace using jquery, you can probably look into JQuery removing '-' character from string it is just an example but you will have an idea.

提交回复
热议问题