开发者

How to achieve String Manipulation in JavaScript

The problem statement is like this: I have a contract. On renewal on every month the contract name should append with renewal identifier. For example at beginning the name is开发者_JS百科 myContract then on first renewal name should be myContract-R1, next renewal name should be myContract-R2 and so on.. On each renewal, the name should automatically change. So in Jquery how can I do this?


This is a JavaScript question, not a jQuery question. jQuery adds little to JavaScript's built-in string manipulation.

It sounds like you want to take a string in the form "myContract" or "myContract-Rx" and have a function that appends "-R1" (if there's no "-Rx" already) or increments the number that's there.

There's no shortcut for that, you have to do it. Here's a sketch that works, I expect it could be optimized:

function incrementContract(name) {
  var match = /^(.*)-R([0-9]+)$/.exec(name);
  if (match) {
    // Increment previous revision number
    name = match[1] + "-R" + (parseInt(match[2], 10) + 1);
  }
  else {
    // No previous revision number
    name += "-R1";
  }
  return name;
}

Live copy


You can use a regular expression for this:

s = s.replace(/(-R\d+)?$/, function(m) {
  return '-R' + (m.length === 0 ? 1 : parseInt(m.substr(2), 10) + 1);
});

The pattern (-R\d+)?$ will match the revision number (-R\d+) if there is one (?), and the end of the string ($).

The replacement will return -R1 if there was no revision number before, otherwise it will parse the revision number and increment it.


how you get renewal number? Calculating from date, or getting from database?

var renewal = 1,
    name = 'myContract',
    newname = name+'R'+renewal;

or maybe like

$(function(){
function renew(contract){
    var num_re = /\d+/,
        num = contract.match(num_re);
    if (num==null) {
        return contract+'-R1';
    } else {
        return contract.replace(num_re,++num[0]);  
    }
}

var str = 'myContract';  

   new_contract = renew(str); // myContract-1
   new_contract = renew(new_contract); // myContract-2
   new_contract = renew(new_contract); // myContract-3

});

Here jQuery can't help you. It's pure JavaScript working with strings

P.S. I have here simple reg exp, that's not concrete for your example (but it works). Better use reg-exp from example of T.J. Crowder

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜