Home > OS >  Javascript delete specific text with Regex
Javascript delete specific text with Regex

Time:08-04

I need help with my js regex code.

The text:

9.The average American walks 3,000 to 4,000 steps a day.

From inspect element:

<h3 id="the-average-american-walks-3000-to-4000-steps-a-day">
<span>9.</span> The average American walks 3,000 to 4,000 steps a day.
</h3>

My output:

The average American walks 3,to 4,steps a day.

Expected output:

The average American walks 3,000 to 4,000 steps a day.

My code:

$(".round-number")
            .find("h3")
            .each(function (i, el) {
                let row = $(el).text().replace(/(\s )/g, " ");
                row = $(el)
                    .text()
                    .replace(/[0-9] . /g, "")
                    .trim();
                console.log(`${row}`);
                healthArray.push(row);
            });

CodePudding user response:

If you want to delete just a single occurrence of the number then you do not need a g flag in the regexp.

Then if it's alway in the beginning of the sentence you can use ^ symbol to make sure regexp only search at the start of the string

You also need to escape . symbol when you use it in regexp, like this - \., otherwise regexp reads it as "any" symbol.

And the last, do trim before applying regex.

Example:

$("h3").each(function (i, el) {
    const row = $(el)
        .text()
        .trim()
        .replace(/^[0-9] \. /, "");
    console.log(`${row}`);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<h3 id="the-average-american-walks-3000-to-4000-steps-a-day">
  <span>9.</span> The average American walks 3,000 to 4,000 steps a day.
</h3>

  • Related