I am looking for a way to replace the quotes with “corrected” quotations marks in an user input.
The idea
Here is a snippet briefly showing the
It is working for many of the cases, at the exception of when the "word" is at the very beginning or the very end of a sentence or a line.
To solve that problem, you can use an alternation of a beginning/end of line assertion and the space, capture that, and use it in the replacement:
this.value = this.value.replace(/(^| )"/g, '$1“');
this.value = this.value.replace(/"($| )/g, '”$1');
The alternation is ^|
/ $|
. The capture group will be ""
if it matched the assertion, or " "
if it matched the sapce.
$('#myInput').on("keyup", function(e) {
this.value = this.value.replace(/'/g, '’');
// The below doesn't work when there's no space before or after.
this.value = this.value.replace(/(^| )"/g, '$1“');
this.value = this.value.replace(/"($| )/g, '”$1');
});
However, you've said you want to avoid "escaping" characters on user input. I'm not sure where you're planning to use it, but something like the above is almost never the approach to use to a problem with that sort of description.