One of my fields has words which may or may not have parentheses. Since I want to launch a search of the word on a website with a link when clicking the word or a button, I would like to use the {{text:Field}} functionality to add the word to the URL. However, if the word has () within it, the search will fail.
Is there a way to eliminate these before adding them to the URL?
I’ve thought of creating a new field with the word without the parentheses (just batch copying the word and replacing the parentheses with noting) and using that field for the search instead, which would serve as a workaround. But this deck has already way too many fields, so if there is an alternative I’d like to try it.
<div id="link_output"></div>
<script>
var unparsed_link = "<a href='https://dictionary.cambridge.org/dictionary/spanish-english/{{text:Field}}'>{{text:Field}}</a>";
if (unparsed_link) {
var parsed_link = unparsed_link.replace(/\((.*?)\)/g, '$1');
document.getElementById("link_output").innerHTML = parsed_link;
}
</script>
The code replaces acordar(se) with acordarse.
If you want to replace it with acordar instead, try deleting $1 from var parsed_link = unparsed_link.replace(/\((.*?)\)/g, '$1');.
Regarding the image issue:
the problem appears to be that you are using double quotes to wrap the attributes src, style and title, but they were already used for the variable.
If you use double quotes for the variable, you need to use single quotes for the attributes, and vice versa.
E.g., this version of the code seems to work correctly on my end:
var unparsed_link = "<a href='https://dictionary.cambridge.org/dictionary/spanish-english/{{text:Field}}'><img src='_book-open-text.svg' style='height: 25px;' title='Definition"></a>';
Or alternatively:
var unparsed_link = '<a href="https://dictionary.cambridge.org/dictionary/spanish-english/{{text:Field}}"><img src="_book-open-text.svg" style="height: 25px;" title="Definition"></a>';
Regarding “{{Field}} vs {{text:Field}}”:
{{text:Field}} is useful when the field contains HTML tags (e.g. <br>, <u></u>, <b></b> etc.), so that they are not included in the link. If the field doesn’t contain any HTML tags, it shouldn’t make much of a difference if you use one or the other. That being said, using {{text:Field}} should almost always be the best practice.
Regarding “show acordar(se) but redirect to acordarse”:
removing the g (global) modifier ensures that the regex will only remove the first pair of parentheses it encounters (i.e., the ones in the href attribute of the link, not affecting those of the displayed text).
To remove the g (global) modifier, change the regex from unparsed_link.replace(/\((.*?)\)/g, '$1')
to unparsed_link.replace(/\((.*?)\)/, '$1')
If sometimes the field contains more than one pair of parentheses (e.g., a(cor)dar(se) ), it should still be possible to adjust the script, but more complex changes would be required.