jquery (js) string replace problem
i want to highlight all digits in string, i try to cover matched digits with tag but cann't! Here is my code
regexp = /[1-9]/g;
//$("#task").val() it's my input
title = $("#task").val().replace(reg开发者_如何学运维exp,'<span class="int">$1</span>');
$1 - i found in google some samples, where $1 must be first matched value, but it's dosn't work!
$1
will replace the first capture group matched in the regex.
Your regex doesn't have any capture groups, so it doesn't do anything.
You need to wrap the regex in parenthesis to make it capture.
For example:
title = $("#task").val().replace(/([1-9])/,'<span class="int">$1</span>');
Note that this won't match 0
; you may have meant [0-9]
.
Also note that this will surround every single digit with a <span>
tag. If you actually want to surround each number with a span tag (eg, <span class="int">123</span>
), you'll need to add a +
to tell it to match one or more digits, like this:
title = $("#task").val().replace(/([0-9]+)/,'<span class="int">$1</span>');
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>
精彩评论