JS替换不在字符串上工作 [英] JS replace not working on string

查看:134
本文介绍了JS替换不在字符串上工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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); 

哈希值仍然存在。

不确定我缺少什么?

推荐答案

.replace()返回一个新字符串(它不会修改现有字符串)所以你需要:

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

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

您可能还应该 question_num 一个字符串虽然自动类型转换可能会为您处理。

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

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

仅供参考,在Javascript中,字符串是不可变的 - 永远不会修改现有字符串。所以任何修改字符串的方法(如 concat 替换 slice substr substring toLowerCase toUpperCase 等等......)总是返回一个新字符串。

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.

这篇关于JS替换不在字符串上工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆