jQuery替换为变量? [英] jQuery replace with variable?

查看:85
本文介绍了jQuery替换为变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对这样的字符串执行replace:

I'm trying to do a replace on a string like this:

$('#example_id').replace(/abc123/g,'something else')

但是abc123实际上需要是一个变量.

But the abc123 actually needs to be a variable.

所以像这样:

var old_string = 'abc123'
$('#example_id').replace(/old_string/g,'something else')

那我该如何在替换函数中使用一个变量?

So how would I use a variable in the replace function?

推荐答案

$('#example_id')的第一个将为您提供jQuery对象,您必须在其html或值内替换字符串.试试这个.

First of $('#example_id') will give you a jQuery object, you must be replacing string inside its html or value. Try this.

var re = new RegExp("abc123","g");
$('#example_id').html($('#example_id').html().replace(re, "something else"));

这篇关于jQuery替换为变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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