How to generate any number into a variable?

Hi. I have some jquery which is:

output_fields:{
        line_1: '#8_999_1',
        line_2: '#8_999_2'

   	},

However. I want to replace the digit 8 with any number. Its always going to end in ‘_999_1’ or ‘_999_2’ but the 8 could be any number.

I feel it needs to be a wildcard. I cant find a javascript way to do this. So can this be done in php? It needs to be something like:

line_1: ‘#<?=* ?>_999_1’,

Where * can be any number from 1 - 9.

Does that make sense?
Thanks

Try this:

<?php 

$output_fields = [
  'line_1' => '#8_999_1',
  'line_2' => '#8_999_2'
];
echo '<pre>';
  echo '$output_fields ==> '; 
  print_r($output_fields);

  $new = [];
  foreach($output_fields as $id => $tmp):
	$new[$id] = str_replace('#8', '#XXX', $tmp);
  endforeach;
  print_r($new);
echo '</pre>';


### Output: ```

$output_fields ==> Array
(
[line_1] => #8_999_1
[line_2] => #8_999_2
)

$new ==> Array
(
[line_1] => #XXX_999_1
[line_2] => #XXX_999_2
)

Thanks John. But now I have XXX where there should be a number(?)

To clarify: 8_999_1 could be x_999_1 (where x is any number from 1 - 9).

Where is this code being used? What are you doing with output_fields?

This is some jquery that is included in every page of the website.

Each page has a form on it. This jquery is used to make the form work. All the fields on all the pages wi be in the format #8_999_1, #8_999_2 etc… BUT on each page the ‘8’ will change. It could be any number. (the page id dictates this number). So Im trying to have this script work across all forms without having to do a load of if/else statements.

I hope Ive clarified it. Its kinda hard to explain. :slight_smile:

Could you define the value of the number in the page itself, then use a loop to create the array? So your script that you want to work across all forms would effectively use a value passed into it. Whatever generates the form could create that variable, or if the forms are hard-coded it could be too.

So the “any number” is not a random number inserted in that place, but the page ID. That’s quite a different piece of code.

Try using the PHP function and passing the three relevant values before creating the jQuery array.

It is difficult to suggest a solution when only a small script snippet is available.

However you do this, it will be very inefficient in terms of code.

const regexp = /\d_999_\d+/;

const elements = $('[id]').filter(function(index, element) { return regexp.test(element.id); });

That first matches all elements that have an id attribute (yes, that is expensive) and then loops all of them to throw out any elements that don’t match your format (one digit_999_one or more digits)

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.