Problem with jQuery (js)

I want to highlight all the numbers in a line, I try to cover the corresponding numbers with tags, but cann't! Here is my code

regexp = /[1-9]/g;
//$("#task").val() it my input
title = $("#task").val().replace(regexp,'<span class="int">$1</span>');

$ 1 - I found some samples on Google where $ 1 should be the first matching value, but it doesn't work!

+3
source share
2 answers
var regexp = /(\d+)/g; // use \d to match all digits, + to capture one or more
var title = 'testing 123'.replace(regexp,'<span class="int">$1</span>');

Result: testing <span class="int">123</span>

+2
source

$1 will replace the first capture group agreed in regular expression.

There are no capture groups in your regex, so it does nothing.

You need to wrap the regex in parentheses to make it a capture.

For instance:

title = $("#task").val().replace(/([1-9])/,'<span class="int">$1</span>');

, 0; , , [0-9].
, <span>. span (, <span class="int">123</span>), +, , , :

title = $("#task").val().replace(/([0-9]+)/,'<span class="int">$1</span>');
+4

Source: https://habr.com/ru/post/1727519/


All Articles