Javascript JS替换不适用于字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12231644/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:27:42  来源:igfitidea点击:

JS replace not working on string

javascriptjquery

提问by Quadrant6

Trying to replace all instances of # in a string with a variable. It's not working but not retuning any error either.

试图用变量替换字符串中 # 的所有实例。它不起作用,但也没有重新调整任何错误。

answer_form = '<textarea name="answer_#" rows="5"></textarea>'+
              '<input type="file" name="img_#" />';

question_num = 5;

answer_form.replace(/#/g, question_num); 

The hashes remain.

散列仍然存在。

Not sure what I'm missing?

不确定我缺少什么?

回答by jfriend00

.replace()returns a new string (it does not modify the existing string) so you would need:

.replace()返回一个新字符串(它不会修改现有字符串),因此您需要:

answer_form = answer_form.replace(/#/g, question_num); 

You probably should also make question_numa string though auto type conversions probably handle that for you.

您可能还应该创建question_num一个字符串,尽管自动类型转换可能会为您处理。

Working example: http://jsfiddle.net/jfriend00/4cAz5/

工作示例:http: //jsfiddle.net/jfriend00/4cAz5/

FYI, in Javascript, strings are immutable - an existing string is never modified. So any method which makes a modification to the string (like concat, replace, slice, substr, substring, toLowerCase, toUpperCase, etc...) ALWAYS returns a new string.

仅供参考,在 Javascript 中,字符串是不可变的——现有的字符串永远不会被修改。因此,任何对字符串进行修改的方法(如concat, replace, slice, substr, substring, toLowerCase, toUpperCase, 等...)总是返回一个新字符串。

回答by ffffff01

Your code is correct. Just add the value to the variable like this:

你的代码是正确的。只需将值添加到变量中,如下所示:

answer_form = '<textarea name="answer_#" rows="5"></textarea>'+
              '<input type="file" name="img_#" />';

question_num = 5;

answer_form = answer_form.replace(/#/g, question_num);