Obtain the currency symbol from a given price string

My dilemma with extracting currency symbols:

var str1 = '10.00 €';
var str2 = '12.22 $';

I attempted to create a function that would only retrieve the currency symbol:

 function extractCurrencySymbol(str){
    return str.replace(/[0-9.,]/g, '');
}

However, this function only removes digits and punctuation, leaving me unable to get the currency symbol. Any suggestions on how to achieve this?

Answer №1

If we utilize a regular expression to strip away all other characters (numbers, periods, commas, spaces), we will be left solely with the currency symbols

var example1 = '10,00 €';
var example2 = '12.22 $';

function extractCurrencySymbol(str) {
  //eliminate all numbers, spaces, commas, and periods by replacing them with an empty string
  //the result should only be the currency symbols
  return str.replace(/[\d\., ]/g, '');
}

console.log(extractCurrencySymbol(example1));
console.log(extractCurrencySymbol(example2));

Answer №2

Simply select the final character in the given string

function getLastCharacter(str) {
    return str.trim().charAt(str.length - 1);
}

Answer №3

If you're looking to extract the last character from a string to get the symbol you need, a simple function can do the trick. Since Javascript treats strings as character arrays, you can easily access the last character using the length of the string like this:

function extractSymbol(str){
    return str[str.length-1];
}

I hope this solution proves useful to you! Thank you

Answer №4

The functionality of the Number() method is to convert any data input into an integer. However, if you pass symbols and spaces into it, such as '10,00 €', it will return NaN.

To extract only the symbol from a string in JavaScript, there are built-in methods that can be used together to handle this easily.

If the position of the symbol is known, we can retrieve the symbol at that position using the charAt() method.

function knownLocation(s) {
  return s.charAt(s.length - 1)
}

If the position of the symbol is unknown, but its presence is known, we can utilize the .includes method to check for the symbol and return the character at the index.

function knownValue(s) {
 if (s.includes("$")) {
    return s.charAt(s.indexOf("$"))
 } else if (s.includes("€")) {
   return s.charAt(s.indexOf("€"))
 } else {
   return undefined
 }
}

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

Retrieve the keys of a JSON object from an unfamiliar JSON format

I have a challenge involving an algorithm where I need to extract all keys (including nested objects and arrays of objects) from a JSON file with unknown structures and store them in one array. { "key": "value to array", "key": [{ "key": { "k ...

Resetting text in an input field using CSS

Here is the fiddle link for reference: http://jsfiddle.net/a765q/1/. I noticed that when I click the reset button, the text color changes to grey. Any ideas on how to fix this? ...

Encountering a TypeScript error when using Redux dispatch action, specifically stating `Property does not exist on type`

In my code, there is a redux-thunk action implemented as follows: import { Action } from "redux"; import { ThunkAction as ReduxThunkAction } from "redux-thunk"; import { IState } from "./store"; type TThunkAction = ReduxThunk ...

In the realm of JavaScript, removing a DOM element can sometimes feel like an

For my project, I am using JavaScript, DOM, and AJAX to create pages. I am trying to figure out how to check if an element already exists and, if it does, remove it. This is what I have tried: var elementL = document.getElementById('divLogin'); ...

Organize and display a list of contacts alphabetically by the first letter of their

I have a list of contacts that I need help with. Despite searching on Stack Overflow, I couldn't find the answer. Can someone please assist? Thank you. export const rows = [ { id: 1, name: 'Snow', email: 'Jon', co ...

What is the process for retrieving my dates from local storage and displaying them without the time?

Having an event form, I collect information and store it in local storage without using an API. However, I face a challenge when extracting the startdate and enddate out of localstorage and formatting them as dd-mm-yyyy instead of yyyy-mm-ddT00:00:00.000Z. ...

Creating intricate filters using React's map functionality

QUESTION HAS BEEN UPDATED. I am currently working on implementing a filter for my map, allowing users to specify which options they want to view using multiple selection boxes. However, I am encountering an issue with the page that appears after the user ...

Utilizing Reactjs and Php to Send and Retrieve Form Data

I am currently working with Reactjs (Nextjs) and PHP. I am trying to send form data using Axios, but I am facing an issue where I am unable to retrieve any parameter on the API side. How can I resolve this problem? Below is my current code: const handleSu ...

Customizing MUI DataGrid: Implementing unique event listeners like `rowDragStart` or `rowDragOver`

Looking to enhance MUI DataGrid's functionality by adding custom event listeners like rowDragStart or rowDragOver? Unfortunately, DataGrid doesn't have predefined props for these specific events. To learn more, check out the official documentati ...

Is it possible to check the response headers in Express JS?

To view the incoming request headers, I typically use: req.headers. I am looking to see a comprehensive list of all headers that will be included in the response. Currently, res.headers returns undefined. I understand that I can set response headers usi ...

What is the best way to add a new element with specified text to a group of chosen HTML elements?

Here is some HTML code that selects specific elements: let array = jQuery.makeArray($(".dersprg tr td:nth-child(6)")); The selected elements contain table header text and some irrelevant data. While I can interpret the irrelevant data using if statements ...

What is the best way to identify the position of an element in an array given my specific circumstances

I am trying to utilize the ng-repeat directive in order to display an array. Here is what I have: <div ng-repeat="stu in school"> <div>{{stu.name}}</div> <div>{{stu.grade}}</div> </div> JavaScript $scope.scho ...

Instead of modifying the selected class, jQuery generates inline styles

Utilizing the following code to dynamically create a class: $("head").append('<style type="text/css"></style>'); var newStyleElement = $("head").children(':last'); newStyleElement.html('.move{transform: translateX(1 ...

Reading a JSON file using Javascript (JQuery)

Struggling to figure out how to handle a JSON file using JavaScript. Here are the details : { "streetCity": { "132":"Abergement-Clemenciat", "133":"Abergement-de-Varey", "134":"Amareins" } } I am attempting to access ...

What is the best way to transfer GitHub OAuth information to a client?

I am in the process of implementing Github authorization and then sending received JSON data to the client. After doing some research, I came across a helpful tutorial at The tutorial suggests following this path: "/" -> "/login" -> "/redirect" -&g ...

Having trouble maintaining the original events on a cloned element

My goal is to duplicate an element passed into a function and retain all associated events, including ones like $('.example').on('click', function(e) ... )} that are defined within the document ready. Here's what I'm trying: ...

Creating new 'morphing' geometry in Three.js with all required buffers: A step-by-step guide

I have implemented a web-worker to load a .json file that contains an animated 3D model. To optimize performance, I am transferring Float32Array buffers for the main arrays (vertices, normals, etc.) back to the UI thread, leveraging the benefits of transfe ...

Altering the properties of every item within a v-for loop's array

I'm currently exploring Vue's approach to writing JavaScript. Let's consider this situation: In the .vue template <button v-on:click="biggerFont()" class="btn btn-s btn-default" type="button" name="button">A</button> < ...

Evaluate the functionality of an Angular controller method that interacts with the Document Object Model (

We currently have an AngularJS controller that contains the following function: $scope.testMe = function() { return $('#test'); } So, how can we effectively test this function? We attempted a Karma test as shown below: describe(' ...

Tips for eliminating empty trailing values and Carriage Returns from a JavaScript array

I needed a way to eliminate empty elements and Carriage Returns from the end of an array. Here's an example of what my array looks like: Input arr: ['', 'Apple', '', 'Banana', '', 'Guava', & ...