0

I have the following:

        xx = toString( '-' + toString( x ) + '-' );
        z = i.replace( /\-1\-/gi, '-3-' );

This does the replacement as stated, but if I do this:

        xx = toString( '-' + toString( x ) + '-' );
        z = i.replace( /\-1\-/gi, xx );

the replacement is "unknown object" I need the later implementation to work since the replacement will vary. How?

  • 1
    What do you expect `toString(`…`)` to do? String conversion is done with [`String(`…`)`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/String). `toString()` calls [`Object.prototype.toString`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/toString) [without context](/a/3127440/4642212); the argument is ignored. – Sebastian Simon Aug 01 '21 at 17:14
  • Make sure to provide the sample strings and the desired output string! What are `xx` and `x` ? `z` should look like...? Please, [edit], create a [mcve]. – Roko C. Buljan Aug 01 '21 at 17:14
  • Why do you assume this has anything to do with `replace`? Have you looked at what `toString( '-' + toString( x ) + '-' )` is? Use the [browser console (dev tools)](//webmasters.stackexchange.com/q/8525) (hit `F12`). – Sebastian Simon Aug 01 '21 at 17:20

1 Answers1

0

You have implement the .toString() function in a wrong way. Check this out for more details Object.prototype.toString() and Array.prototype.toString()

A quick fix for your code:

let xx = `-${x.toString()}-`
let z = i.replace( /\-1\-/gi, xx );
Mike
  • 56
  • 1
  • 9