Obtain the parameters of a JavaScript function that is stored as a string

While parsing a webpage, I came across a JavaScript function stored as a string:

"translate(737.4170532226562,136.14541625976562)" 

My goal is to extract the two parameters from this function. I currently parse the string up to the '(' and ',' and ')', but I am curious if there is an alternative method to retrieve the parameters in this string function.

Answer №1

If you need to extract specific values from a string, regular expressions can be very useful. Here's an example of a regex pattern you could use: /([\d\.]+),([\d\.]+)/

var inputString = "translate(737.4170532226562,136.14541625976562)";
var matches = /([\d\.]+),([\d\.]+)/.exec(inputString);
var value1 = matches[1];
var value2 = matches[2];

document.write(['First value: ', value1, '<br> Second value: ', value2].join(''))

Answer №2

Feeling a bit excessive at the moment, but my boredom lead me to create a function name parser. This little tool extracts both function names and arguments from text strings.

var inputText = "rotate(125.4170532226562,245.14541625976562)";

function FunctionNameParser(text)
{
  this.text = text;
  this.length = text.length;
  this.position = 0;
  this.currentChar = '0'
  this.getNextChar();
}
FunctionNameParser.prototype.isName = function() {
    return this.currentChar <= 'z' && this.currentChar >= 'a' || this.currentChar <= '9' && this.currentChar >= '0' || this.currentChar == '.'    
}
FunctionNameParser.prototype.getNextChar = function() {
    this.currentChar = this.text[this.position++];
}
FunctionNameParser.prototype.getName = function() {
  var name = "";
  while(parser.isName()) {
    name += parser.currentChar;
    parser.getNextChar();
  }
  return name;
}

var parser = new FunctionNameParser(inputText);
var funcName = parser.getName();
var argumentsList = [];

if(parser.currentChar == '(') {
  parser.getNextChar();
    args.push(parser.getName());
    while(parser.currentChar == ',') {
        parser.getNextChar();
        argumentsList.push(parser.getName());
    }
} else {
    throw new Error("Function name must be followed by ()")
}

console.log(funcName, argumentsList);

Answer №3

Although slightly delayed, I believe this method streamlines the process of obtaining parameters or executing a custom function with other function parameters.

var funcStr = "translate(737.4170532226562,136.14541625976562)";
function parser(str){
    let fName = str.split('(')[0];
    let evalFunc = str.replace(fName, 'getParams');
    return eval(evalFunc);
}
function getParams(...prms){
    return prms;
}
console.log(parser(funcStr));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Show component featuring checkboxes

Is it possible to show a component when a checkbox is clicked? I am creating a dashboard and need to choose which tools to display on my screen. I have set up checkboxes with v-model="select", value="name of component", and used v-for for list rendering. ...

Uploading a three.js canvas to the server without saving it as a file

Currently, I am in the process of saving an image to the server using a three.js script that I have created. The script looks like the following: actualCode(THREE); function actualCode(THREE) { //Rendering variables const renderer = new THREE.WebG ...

What steps can you take to convert your current menu into a responsive design?

I am currently developing a website using PHP, HTML, and CSS. The site is not responsive, and I want to make the menu responsive. My global navigation and admin interface are not adapting properly as they are designed using tables. Is there a method I can ...

Custom markup parser failing to interpret line breaks

I've developed a custom markup parser for my application, and it generally functions flawlessly. However, when the opening and closing tags are placed on separate lines, an issue arises. For instance: <test>This is a test</test> works p ...

Tips for transferring information from a React template to a Flask API

I am exploring the use of a sign-in template, but I'm uncertain about how to send data from this template to my Flask API. I have come across information suggesting that states are only used in components. Is this factual? I attempted to call the Regi ...

What is the best way to establish a default selection in Angular?

After retrieving JSON data from the server, it looks something like this: $scope.StateList = {"States": [ { "Id": 1, "Code": "AL", "Name": "Alabama" }, { "Id": 2, "Code": "AK", "Name": "Alask ...

Using Typescript to Declare Function and React Component Types

Currently challenging myself to delve into Typescript (ugh). Usually, I can deduce the appropriate type by analyzing the return values. Nonetheless, in this particular scenario, that method is proving ineffective. type SomeReactAProps = { Type1: ReactEle ...

Disable event listener when the controls are unlocked using the pointerlock controls in three.js

While navigating a model with threejs pointerlock controls, clicking on specific sections of the model directs users to different parts of the site. However, an issue arises when the camera is centered over a section and the user exits the pointerlock. Upo ...

Strange Dojo Error Reporting Issue - 'function is undefined' error incorrectly reported by dojoBuild

Strange issue alert! In development mode, everything seems to be working fine. However, when I run it through dojoBuild, a particular modal is displaying inconsistent behavior. At times, the error message 'undefined' is not a function pops up, s ...

Determine whether a value is present in a JavaScript object in real-time while typing in a TextBox with the help of angular

Within a textbox, users have the freedom to input any value. Upon each keystroke, I must validate whether that value already exists in $scope.arrayObject. A common approach involves attaching a key-up event handler to the textbox and performing the necessa ...

Using a combination of stringify, regular expressions, and parsing to manipulate objects

As I review code for a significant pull request from a new developer, I notice their unconventional approach to editing javascript objects. They utilize JSON.stringify(), followed by string.replace() on the resulting string to make updates to both keys a ...

Using jQuery to modify the CSS of a div located outside of an iframe

Currently, I am developing a straightforward script. Firstly, here is all of the code that I have: <script src="//code.jquery.com/jquery-1.10.2.js"></script> <script type="text/javascript"> function SuperWebF1() { $("#outerd ...

Leveraging JavaScript within PHP script

I am currently developing a booking system that involves creating events in a table using PHP. I want to implement a script that will run when a user tries to book an event and then submits the form to PHP. This script will help me determine if the user ha ...

Utilizing Node.js Express' put method for uploading files

Currently, I am attempting to complete a file upload using XMLHttpRequest. The process involves splitting the file into chunks of 10KB each. On the server side, the code looks like this: app.route('/upload/').put(function(req, res, next) { ...

Managing an array within the state of a React JS component

While I have been utilizing React state to store some data, I've encountered an issue with arrays. Ints and strings work fine, but for some reason arrays are not cooperating. Within my component constructor, I have: constructor(props) { super(pr ...

The AngularJs project is currently experiencing issues when trying to function as a single page web application

I'm currently working on incorporating AngularJS into an existing web project that uses jQuery. Here is a snippet of my code: <div class="medya" ng-repeat="d in data" masonry-item-dir> <a href="{{d.Url}}" class="onizleme"><img src="{ ...

Guide on merging all Vue js functions into a single js file?

As a newcomer to vue.js, I am in the process of consolidating several functions into one js file. Here is an example: example.js: function containObject(obj, list) { for (let i = 0; i < list.length; i += 1) { if (list[i] === obj) { return ...

What is the best way to assign user input to my JavaScript variables?

As a newcomer to programming, I am eager to develop an app that utilizes the numerical values inputted by customers as variables for calculations. How can I extract the value from an input using JavaScript? For instance, how can I subtract one input value ...

Creative Solution for Nested Forms

I am currently facing a challenge with nested forms in my PHP project. I need to include a form for AJAX image upload within another form so that I can pass the file path to the main form. The example code snippet is provided below; <form> <f ...

Typescript enhances React Native's Pressable component with a pressed property

I'm currently diving into the world of typescript with React, and I've encountered an issue where I can't utilize the pressed prop from Pressable in a React Native app while using typescript. To work around this, I am leveraging styled comp ...