Sadikhasan
Sadikhasan

Reputation: 18600

Find second digit from string and replace with new digit

I have following string example. I want to find second digit from string and replace with other random digit. I have random digit but problem is find second digit and replace with new digit. How achieve this?

1. "data[KPI][0][rows][0][name]"
2. "data[KPI][0][rows][1][name]"
3. "data[KPI][0][rows][2][name]"

Expected Output

1. "data[KPI][0][rows][4][name]"
2. "data[KPI][0][rows][5][name]"
3. "data[KPI][0][rows][6][name]"

Upvotes: 0

Views: 396

Answers (3)

vks
vks

Reputation: 67988

\d+(?=[^\d]*$)

Try this.See demo.

http://regex101.com/r/uV3aL0/32

var re = /\d+(?=[^\d]*$)/gim;
var str = 'data[KPI][0][rows][0][name]\ndata[KPI][0][rows][1][name]\ndata[KPI][0][rows][2][name]';
var subst = '';

var result = str.replace(re, subst);

Upvotes: 1

Dimag Kharab
Dimag Kharab

Reputation: 4519

Hope this helps,

Java-Script way

var mystr    = "data[KPI][0][rows][0][name]";

var regex       = /(data\[\D{1,}\[\d{1,}]\[\D{1,}\])(\[\d{0,}])(\[\D{0,}])/;

console.log(mystr.replace(regex,"$1[DesiredNumber]$3"));

PHP Way

$str          = "data[KPI][0][rows][0][name]";

$regex        = "/(data\[\D{1,}\[\d{1,}]\[\D{1,}\])(\[\d{0,}])(\[\D{0,}])/";

$replacements =  '${1}[YourNumber]${3}';

echo preg_replace($regex, $replacements, $str);

Upvotes: 1

Neeraj
Neeraj

Reputation: 4489

Hey please try this one:

 var str="data[KPI][0][rows][0][name]";
 var Result=  str.replace(/(\[\d\]\[[^\]]+\])\[\d\]/, "$1[YourCharTo Replace]");

Hope it helps

Upvotes: 1

Related Questions