Switching from "Straight Quotes" to "Curly Quotes"

Looking for a solution to convert regular straight quotes into curly quotes in a Javascript-based rules engine application. Rather than just using a simple string.replace for ["], I need a method that will insert the correct curly quote depending on its position.

My idea is to replace the first occurrence of a quote with a left curly quote and alternate the following ones between left and right curly quotes. Is there a way to achieve this using Javascript?

Answer №1

To add emphasis to text, you can surround words with left and right curly quotes.

str = str.replace(/"(?=\w|$)/g, "“");
str = str.replace(/(?<=\w|^)"/g, "&#8221;"); // Make sure your programming language supports look-behind

If you want to also consider punctuation, you can modify the regular expression:

/(?<=[\w,.?!\)]|^)"/g

[Edit:] In languages like Javascript that do not support look-behind, you have a couple of options:

str = str.replace(/"/g, "&#8221;"); // Replace all quotes with right curly quotes
// or...
str = str.replace(/\b"/g, "&#8221;"); // Replace quotes after word boundaries with right curly quotes

(Keeping the original solution above for those using a language that does support look-behind)

Answer №2

Have you explored the capabilities of Pandoc? It seems that with the addition of the --smart flag, it effectively manages quotes in various scenarios (such as ’tis and ’twere).

Recently, I developed a JavaScript tool for enhancing typography which includes quote replacement functionality. While my implementation is based on an algorithm recommended by Renesis, there is currently a failed test awaiting a more sophisticated solution.

If you are interested in using or contributing to my code, feel free to take a look at: jsPrettify. The function jsprettify.prettifyStr accomplishes what you need. For those avoiding the Closure dependency, an older standalone version is available, which even executes successfully in Rhino.

Answer №3

When 'foo "foo bar" "bar"' is passed through a replace function that targets patterns surrounded by double quotes and replaces them with the same text surrounded by curly quotation marks, the output becomes: 
'foo “foo bar” “bar”'.

Answer №4

This code snippet modifies every quote by replacing it with stylized versions (although orphaned quotes are excluded in this specific case).

str.replace(/\"([^\"]*)\"/gi,"&#8220;$1&#8221;");

This method works flawlessly, assuming the text being modified does not already contain errors with double quotes. It's important to note that in English, quotes should never be nested.

Answer №5

It's not a simple task to handle something like that in general, as each double-quote character in the content requires careful interpretation. My approach would involve gathering all relevant text nodes and meticulously tracking the occurrence of double quotes to determine the appropriate replacement entity for each instance.

Answer №6

After searching for the perfect solution, I couldn't find exactly what I was looking for. Here is the workaround that proved to be effective.

value = value.replace(/(^|\s)(")/g, "$1“"); // Replacing starting quotes or those following spaces 
value = value.replace(/"/g, "”"); // Turning all other quotes into smart curly ones

I'm dealing with a small textarea where I needed to swap out regular quotes with curly quotes. This simple script runs on keyup, aiming to mimic the behavior of Microsoft Word's smart quote feature.

Answer №7

Preserving this information for the future.

Upon the recommendation of @Steven Dee, I headed over to Pandoc's website.

I prefer utilizing established and well-tested tools over creating my own regex solutions. Custom regex patterns can be too aggressive or not aggressive enough, and they often overlook important details like word boundaries and punctuation. Pandoc covers most, if not all, of these nuances.

To utilize Pandoc from the command line (add the --smart flag for smart quotes), you can use:

pandoc --smart --standalone -o output.html input.html

Note that employing a command-line script may not align with the original poster's request for JavaScript implementation. (See: Executing shell commands in JavaScript)

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

What is the best method for implementing ajax in Codeigniter?

Exploring the best approach to writing ajax in CodeIgniter. Is it acceptable to write ajax in views, or is it better to create a new directory named assets at the root of the CodeIgniter project folder and relocate all scripts to a js folder within our a ...

How can I retrieve x-data from an external file using Alpine.js?

I recently started exploring Alpine.js and grasped the fundamentals, but I'm facing challenges when trying to move functions outside of inline script tags. Consider this snippet from index.html: <div x-data="{ loading: false }"/> &l ...

What steps are involved in developing an Angular library wrapper for a pre-existing Javascript library?

Imagine having a vanilla Javascript library that is commonly used on websites without any frameworks. How can you create an Angular library that can be easily installed via npm to seamlessly integrate the library into an Angular application? The process o ...

Tips for looping through nested JSON data in Google Sheets

In my attempt to iterate through the nested "line_items" element in a JSON response triggered by a post event, I aim to populate a Google Sheets spreadsheet using Google Apps Script. My objective is to write the elements within each "line_item" into new ro ...

Converting a decimal Unicode to a string in Javascript/Node: a beginner's guide

In my database, I have Arabic sentences that contain decimal unicodes for quotation marks and other elements. For example, here is a sample text: "كريم نجار: تداعيات &#8220;كورونا&#8221; ستغير مستقبل سوق السي ...

Transforming instance of a Class into Json format for WebService

My goal is to retrieve an object of the Product class as a Json for a webservice. Despite successfully loading all the values into the object, I encounter an error when trying to return it as Json. Below is my method: <AllowAnonymous> <HttpGet&g ...

Patience is key for a fully completed JSON in JavaScript

I recently came across a similar discussion on Stack Overflow, but it involved using JQuery which I'm not using. My issue is that I need to ensure my JSON data is fully loaded before calling my function. I understand the concept of using a callback, ...

The impact of Ajax on jQuery document loading within an Ajax form

I'm currently using jQuery to change the colors of cancelled bookings in a Drupal view, and it's working well. jQuery(document).ready(function(){ jQuery(".bookingstatus:contains('Cancelled')").css("color","red"); }); However, when ...

Can jQuery help me identify which <input type='image> was clicked within a form containing several submit images?

Consider this hypothetical scenario: <form> <input type="text" name="some_name" value="val" id="some_name"> <input type="image" value="action" alt="Add To Cart" name="add" src="/images/submit.gif"> <input type="image" value="act ...

Activate filtering beyond the AngularJS datatable

Currently, I am experimenting with a codepen to understand how to filter data based on a clicked span element. The table is where the data is displayed and I'm looking for a way to trigger filtering outside of it. While the angularjs documentation spe ...

Checking the validity of date inputs - microservice for timestamps

I'm encountering an issue while attempting to validate my date input. I've tried using moment js, but it seems there's a problem. The error message "date invalid" keeps popping up! Here is the code snippet: app.get("/api/timestamp/:date_s ...

Attempting to send a request from the front-end to the back-end is resulting in a 404 endpoint error

I encountered an issue while sending a post request from the front end to the backend. The error message I received was: " Error: Request failed with status code 404 " " Had Issues POSTing to the backend, endpoint " My main concern is ...

The querySelector function seems to be identifying the element with the ID "submit" and another input element of type "submit"

My code includes a function that toggles between two elements' style.display values, switching them from "none" to "block" and vice versa. However, I've encountered an unexpected issue where the behavior of the "send" button seems to be linked wi ...

Seeking out all (including potentially relative) URLs on a webpage: Possible strategies to consider

For a coding challenge, I am working on a small python tool to download an entire website locally. In order to view the website offline, I need to convert all URLs to relative URLs. This is necessary to ensure that resource files (such as .js and .css) are ...

What is the solution for displaying just a single panel?

Is there a way to ensure that only the hidden text is displayed when clicking on the button within each panel? Currently, both panels are being revealed simultaneously... import React, { useState } from "react"; import "./styles.css"; export default func ...

Switch focus between two text fields

Within my react application, I have a total of 10 material-UI textfields. The initial 8 textfields are contained within an expansion panel, while the remaining two textfields are housed in another expansion panel. I am seeking to set up a system where auto ...

Is there a way to validate form elements in HTML prior to submitting the form?

In my form, I am utilizing PHP for validation and processing, but I am interested in verifying elements as they are being filled out. Is there a way to check the current value of an element before the form is submitted? ...

What is the best way to structure time and avoid mentioning the server name?

After struggling for days, I am reaching out for help as I encounter a null error and difficulty changing the time format in my code below. Despite my efforts, this issue seems unsolvable. Error #1 ------------------------------ (node:8844) UnhandledPromi ...

Tips for creating a vertical drawer using jQuery and CSS

Hello, I am currently working on developing a drawer component using Ember.js. If you want to view the progress so far, feel free to check out this jsbin http://jsbin.com/wulija/8/edit My goal is to have the drawer look like the following initially: +--- ...

Issue with rendering in React Router

I've been having trouble with React Router in my code. I know that there have been changes from Switch to Routes in React Router Dom v6, but even after making the adjustment, my program just displays a blank screen. Can anyone help me resolve this iss ...