Search code examples
javascriptreact-nativewebviewzingchart

String containing '%d' being converted to 'NaN'


I am rendering ZingChart inside react-native webview. I need to access zingchart's token using %data-day but whenever i try to use %d it prints NaN

Below is the sample code:

import React, { Component } from 'react';
import { Text, View, WebView } from 'react-native';

export default class App extends Component {
  constructor(props) {
    super(props);
  }
  renderWeb = () => {
    return `
      <html>
        <head>
        </head>
        <body>
        <script>
          ${console.log('%d', ':data')}
          </script>
        </body>
      </html>
      `;
  };
  render() {
    return (
      <View style={{ flex: 1 }}>
        <WebView source={{ html: this.renderWeb() }} />
      </View>
    );
  }
}

Can anyone please help me resolving this?


Solution

  • The first argument to console.log is treated as a format string wherein percent characters introduce substitution sequences. They are loosely based on format strings used by the printf function in C. See under "Using string substitutions" in MDN's console article.

    %d consumes the next unconsumed argument of the call to console.log and formats it as a number. Since ':data' is not a number, Chrome converts it to the string 'NAN' in the log when testing in a browser. It is browser dependent however - Firefox converts it to a zero.

    To log the string "%d", double up on the percent sign and code it as "%%d" in the format string. Just like in C :-)