Can you manipulate a number within a string with J

2020-07-27 04:35发布

问题:

I have some strings like so:

<p>It will vary from 100g to 200g</p>
<p>2lbs of meat</p>
<p>3 piles of timber</p>

etc etc

I would like to increment/decrement all numbers in each string. Any pointers?


Additional notes:

  1. No, the number can be anywhere in the string.
  2. @cookie_monster I would like to see if it's possible without the usual operations.

回答1:

A simple solution would be to use a regular expression, for example:

"100g".replace(/\d+/g, function(n) { return +n + 1; }); // 101g

Explanation:

  • The pattern \d+ matches any sequence of one or more digits in a string.
    • This pattern limits you to integers only; if you tried this with "3.5" it would consider this to be two separate integers and the result would be "4.6".
    • If this is a problem, use a pattern like (\d+\.)?\d+ instead.
  • The global flag (g) on the pattern means that this will replace all digit sequences in the string.
    • Remove this if you only want to replace the first instance.
  • The function accepts the substring that was matched (in this case "100") then converts it to a number (+n), adds 1, and returns the result. This result is converted back to a string, and replaces whatever was matched by the pattern.

To do this within an HTML element using jQuery, you could simply use something like this:

$('p').each(function() {
    var e = $(this);
    e.text(e.text().replace(/\d+/g, function(n) { return +n + 1; }));
});


回答2:

You can use a regular expression to match numbers in the string, and a callback function to parse the number and alter it.

Example:

var s = "There are 4 lights.";

s = s.replace(/\d+/g, function(m){
    return parseInt(m, 10) + 1;
});

Demo: http://jsfiddle.net/6YJQx/

To do this on several elements, you can use the text method with a callback:

$('p').text(function(i, s){
    return s.replace(/\d+/g, function(m){
        return parseInt(m, 10) + 1;
    });
});

Demo: http://jsfiddle.net/6YJQx/1/



回答3:

Yes, you can, but to do it you need give numbers in spans. <span> 100g </span>. Then, with jQuery .text, you can increment, decrement etc. the number.