Home >Web Front-end >JS Tutorial >使用正则替换变量_javascript技巧

使用正则替换变量_javascript技巧

WBOY
WBOYOriginal
2016-05-16 19:13:551624browse

我们使用 str.replace(/s/g,"world") 可以将字符 "s" 替换成 "world"
如果要替换一个变量呢? s = "abc" 怎样将全部 abc 替换成 "world" ?

复制代码 代码如下:

str.replace(new RegExp(s,"g"),"world")

s 中不要包含正则元字符 否则会产生错误
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn