替换Javascript无法正常工作

时间:2018-04-16 22:29:28

标签: javascript

我正在尝试使用RegExp替换同一个字符串中的多个单词,但似乎无法正常工作,我在stackoverflow中尝试了一些答案,但没有结果

var _tpl = "time working $times, not now $times"
var reg = "$times"
var regexp = new RegExp(reg, "g")
var replaceFor = 1


var _newTpl = _tpl.replace(regexp, replaceFor)

console.log(_newTpl)

一些建议?

2 个答案:

答案 0 :(得分:2)

你必须逃避正则表达式'将特殊字符传递给new RegExp之前的特殊字符。

var reg = "\\$times"



var _tpl = "time working $times, not now $times"
var reg = "\\$times"
var regexp = new RegExp(reg,"g")
var replaceFor = 1
var _newTpl = _tpl.replace(regexp, replaceFor)

console.log(_newTpl)




答案 1 :(得分:2)

I Hope Below code solves your problem perfectly <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>jQuery UI Datepicker - Default functionality</title> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/timepicker/1.3.5/jquery.timepicker.min.css"> <link rel="stylesheet" href="/resources/demos/style.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/timepicker/1.3.5/jquery.timepicker.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/timepicker/1.3.5/jquery.timepicker.min.js"></script> <script> $( function() { $( "#durationExample" ).timepicker({interval: 60, minTime: '2',maxTime: '6:00pm','showDuration': true}); } ); </script> </head> <body> <div class="col-md-3"> <div class="form-group"> <label for="appt-time">Choose an appointment time: </label> <input id="durationExample" type="text" class="time" /> </div> </div> </body> </html> 是正则表达式中的特殊字符:您必须将其转义。

&#13;
&#13;
$
&#13;
&#13;
&#13;

请注意,您需要两个var _tpl = "time working $times, not now $times" var reg = "\\$times" var regexp = new RegExp(reg, "g") var replaceFor = 1 var _newTpl = _tpl.replace(regexp, replaceFor) console.log(_newTpl)才能在结果字符串中放置单个文字\。如果使用正则表达式语法而不是字符串语法直接创建正则表达式,则只使用一个\

\