Removing double double quotes for Javascript

My problem involves a string that represents longitude/latitude in the format of dd°mm'ss''W (note 2 single quotes after ss).

To convert this string into its decimal representation, I am using the following code snippet:

function dmsTodegrees(val) {
    var s = val.replace('°', ' ');
    s = s.replace("'", ' ');
    s = s.replace("''", ' '); 
    var tokens = s.split(' ');
    var result = Number.parseFloat(tokens[0]) + Number.parseFloat(tokens[1]) / 60 + Number.parseFloat(tokens[2]) / 3600;
    if (tokens[3] === 'W' || tokens[3] === 'S') result = -result;
    return result;
}

However, it appears that s = s.replace("''", ' '); is not functioning as expected, as the two single quotes (') are not being replaced. I am unsure of what mistake I might be making.

Please note that error handling has been omitted in the provided code.

Answer №1

Using /'{1,2}/g allows you to replace all occurrences of single quotes in the given string. If you wish to replace all single quotes without considering the quantity, you can simply use /'+/g

function convertDegrees(val) {
   var s = val.replace('°', ' ');
   s = s.replace(/'{1,2}/g, ' ');

   return s;
}

console.log(convertDegrees("dd°mm'ss''W"));

Answer №2

Are you attempting to replace special characters like °, ', and '' with spaces in order to split the string into separate tokens? Rather than removing these characters and then splitting the string by space, why not just split it directly?

...
var tokens = val.split(/°|'{1,2}/);
...

This method functions as follows:

"12.34°56.78'90.12''W".split(/°|'{1,2}/)
=> (4) ["12.34", "56.78", "90.12", "W"]

Answer №3

When looking at the following code:

s = s.replace("'", ' ');
s = s.replace("''", ' ');

The first line is replacing every single quote "'" with a space, which means the second line will never find two quotes together.

However, it's important to note that the replace method only works on the first occurrence it finds.

Therefore,

"1,2,3,'',4,'',5,''".replace("'", " ").replace("''", ' ')

will result in

"1,2,3, ',4, ,5,''"

It's recommended to refer to @Dij's response for a more efficient solution.

Answer №4

My recommendation would be to utilize single quotation marks (') with escape sequences(\') inside of them when using the replace function.

function dmsTodegrees(val) {
    var s = val.replace('°', ' ');
    s = s.replace('\'', ' ');
    s = s.replace('\'\'', ' ');
console.log(s);
    var tokens = s.split(' ');
    var result = Number.parseFloat(tokens[0]) + Number.parseFloat(tokens[1]) / 60 + Number.parseFloat(tokens[2]) / 3600;
    if (tokens[3] === 'W' || tokens[3] === 'S') result = -result;
    return result;
}
console.log(dmsTodegrees("20°10'30''4"));

Answer №5

Before making any further replacements, ensure you first replace two single quotes with a space and then one single quote with another space. If you replace the single quotes in the wrong order, you might unintentionally turn two single quotes into two spaces, like what happened to you.

s = s.replace("''"," ");
s = s.replace("'"," ");

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

Utilizing Vue.js to Showcase Real-Time Data on an HTML Page

I am attempting to showcase the bill structure on an HTML page by retrieving data in Vue and Axios. There is a table where orders are listed, with each row having a "Print" button. When this button is clicked, I want to display the specific order details i ...

Discovering duplicates for properties within an array of objects in React.js and assigning a sequential number to that specific field

I am working with an array of objects where each object contains information like this: const myArr=[{name:"john",id:1}{name:"john",id:2}{name:"mary",id:3}] In the first 2 elements, the "name" property has duplicates with the value "john". How can I updat ...

Develop a payment confirmation session using Stripe and Node.js

I have set up a POST request using Stripe to handle customer payments let paymentData = { errorMsg:'', key: process.env.STRIPE_PUBLIC_KEY } const session = await stripe.checkout.sessions.create({ payment_method_types: ...

When the button is not clicked, the function method gets invoked in React

When I call the initiateVideoCall method first and have a button called turnOff, it seems to load first without clicking the button. I'm having trouble understanding the issue here. Can someone please help me? Thanks in advance. const constraints = {& ...

limiting the number of HTTP requests within a JavaScript forEach loop

In my current coding situation, I am facing an issue where the HTTP requests are being made simultaneously within a forEach loop. This leads to all the requests firing off at once. const main = async () => { items.forEach(async (i: Item) => ...

HTML - Selecting Different Values in One Drop Down Based on Another Drop Down

When selecting "First Year" in the initial drop-down menu, the options "Sem1" and "Sem2" should be displayed in the second drop-down menu. Similarly, when choosing "Second Year" in the first drop-down menu, the choices "Sem3" and "Sem4" should appear in th ...

Linking the value of an expression to ngModel

There is a specific scenario where I need the ng-model property to bind to a value retrieved from the database as part of the business logic. To illustrate this concept, I have set up an example function TodoCtrl($scope) { $scope.field1 = "PropertyFr ...

Interactive Zoomable Tree with d3.js

I am looking to customize the zoomable icicle plot in d3js by incorporating my own data. Unfortunately, I am unable to locate the "readme.json" file for data modification and cannot get the graph to display on my local machine. Where can I find this elus ...

Changes made in the view of a VueJS application are not being reflected in Laravel when using

Embarking on my first journey with VueJS within a Laravel PHP framework has been quite the adventure. A new project is on the horizon, and I dove in headfirst by making various changes, such as adding new elements and altering titles. However, much to my d ...

Resolve feature for UI routes fails to function upon refreshing the page

My app utilizes UI Route for view routing. When accessing /berlinerliste/, a function is triggered to display an array of objects. If one of these objects is clicked, the view changes to /berlinerliste/{id}/ and shows the details of that specific object. ...

Exporting two functions in JavaScript

Currently utilizing React, Redux, and experimenting with Material-UI integration. The example codes provided by Redux and Material-UI libraries include an 'export' statement at the end. Redux: export default connect(mapStateToProps, actions)(my ...

NodeJs Importing a File

Currently working with NodeJS, I have encountered a challenge. Is it possible to require a JavaScript file in Node similar to how we do in browsers? When using the require() method, I noticed that the JavaScript file called does not have access to global v ...

Counting the number of visible 'li' elements on a search list: A guide

In the following code snippet, I am attempting to create a simple search functionality. The goal is to count the visible 'li' elements in a list and display the total in a div called "totalClasses." Additionally, when the user searches for a spec ...

When converting JavaScript to PHP using AJAX, PHP retrieves an empty array

I am attempting to send a file from JavaScript to PHP using AJAX, but PHP is receiving an empty array. Currently, I am working on creating a web page through which I can pass a file to PHP in order for it to access and save information from the file into ...

Protractor - selecting a hyperlink from a list

Imagine you have a todo application with tasks listed as follows: Walk the dog, Eat lunch, Go shopping. Each task has an associated 'complete' link. If you are using Protractor, how can you click on the 'complete' link for the second t ...

Having trouble with NVM not working correctly in Ubuntu 21.04 Terminal?

Lately, I've been facing challenges with updating my Node.js version, and one method I tried was using node version manager. After downloading the install_nvm.sh file with the command curl -sL https://raw.githubusercontent.com/nvm-sh/nvm/v0.38.0/insta ...

Having trouble retrieving the component state within AgGrid's cellRenderer

When working on my React app using functional components, I encountered an issue with accessing a local state (myObj) within a cellRenderer in AgGrid. The local state is populated via a context object from the parent component based on an API response. Un ...

Go to a distant web page, complete the form, and send it in

As the creator of Gearsbook.net, a social network for Gears of War players, I am constantly striving to improve the site's functionality. Currently, it is quite basic and in need of updates. One highly requested feature by users is the ability to lin ...

Ensure to verify the values of two variables when using a switch case statement

I'm working with two variables that can return true or false. My goal is to display a corresponding text message for each variable if it returns false. How can I effectively handle the ValidCheked and repeatChecked variables in a switch statement? ...

Need help setting up automatic audio playback on your Android device?

I'm aware that autoplay of audio is not supported on Android devices. However, I recently found a website that successfully autoplays music on an Android device: Can someone explain how this is being achieved? ...