简体   繁体   English

提示用户替换字符串中文本的某些部分

[英]Prompt user to replace certain parts of text in a string

I have a program that allows a user to type JavaScript in a textbox, and it executes in an HTML viewer or iframe. 我有一个程序,允许用户在文本框中键入JavaScript,并在HTML查看器或iframe中执行。 There is a drop down with options such as "Insert Image", which inserts 下拉菜单中包含“插入图片”等选项,

var $'Image Name' = document.createElement('img');
$'Image Name'.src = $'Image URL';
$'Image Name'.style.position = 'absolute';
document.body.appendChild($'Image Name');

into the textbox. 进入文本框。 I want the user to select the option "Insert Image", and have a dialog go through each $'' , and ask for something to replace them with, so for the first $'Image Name' , prompt the user for a variable name, and then replace("$'Image Name'", userText) so all the $'Image Name' s get replaced and the user isn't prompted for the same one again. 我希望用户选择“插入图像”选项,并让对话框遍历每个$'' ,并要求用它们替换,因此对于第一个$'Image Name' ,提示用户输入变量名,然后replace("$'Image Name'", userText)以便所有$'Image Name'都被替换,并且不再提示用户输入相同的图像。 Any ideas? 有任何想法吗? I have this replace: 我有这个替换:

replace(/^\$\"|\'.$\"|\'/gi, function ($string) { return prompt($string);});

but it matches the quotes, not the text inside the quotes, and I don't even know regex, if you can solve the regex, I can figure out the rest. 但是它匹配引号,而不是引号内的文本,而且我什至都不知道正则表达式,如果可以解决正则表达式,我可以弄清楚其余部分。

I guess you want something like this: 我想你想要这样的东西:

replace(/\$'([^']+)'/g, function (s, contents) { return prompt(contents); });

though I should mention that this will misbehave if a single-quoted string happens to end with a dollar-sign, or if a double-quoted string happens to contain $' , or whatnot; 尽管我应该提到的是,如果单引号的字符串恰好以美元符号结尾,或者双引号的字符串恰好包含$'或其他,则这将是错误的; do you need to be able to handle these sorts of cases? 您需要能够处理这类案件吗? (It's not obvious from your question whether you completely control the contents of the textarea, or whether it's something your users might be editing.) (从您的问题中,您是否完全控制了文本区域的内容,还是用户可能正在编辑的内容,这并不明显。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM