在整个字符串中查找两个字符之间的字符

时间:2013-09-05 18:19:10

标签: jquery

我是Jquery的新手。我有Dear < EmployeeList >, kindly complete your joining documentation and submit the same to < DepartmentList > latest by < DateCalendar >

之类的字符串

我想替换“&lt; EmployeeList&gt;”到“ABC”。

同样的规则适用于其他“&lt;&gt;” 。 整个字符串不固定,可能会改变。

Dear < EmployeeList >, welcome to < FreeTextCompany > We wish you a long and prosperous association with us.

所以请记住字符串不是固定它只是一个模板。

请帮帮我

我正在尝试查找字符串并替换为我的字符串但能够执行此操作

  var start_pos = test_str.indexOf('<') + 1;
            var end_pos = test_str.indexOf('<', start_pos);
            var text_to_get = test_str.substring(start_pos, end_pos)
            $('#MainContent_lblSMSTemplate').text().replace(text_to_get, "");

2 个答案:

答案 0 :(得分:1)

你去:

function replaceString(string, replaceObj) {
   for (var key in replaceObj) {
      string = string.replace(new RegExp(key, 'gi'), replaceObj[key]);
   }

   return string;
}

var replaceObject = {
     '< EmployeeList >' : 'ABC',
     '< DepartmentList >' : 'DepHr',
     '< DateCalendar >' : '12march'
};

var string = 'Dear < EmployeeList >, kindly complete your joining documentation and submit the same to < DepartmentList > latest by < DateCalendar >';

var newString = replaceString(string, replaceObject); // ouput will be: Dear ABC, kindly complete your joining documentation and submit the same to ABC latest by ABC

答案 1 :(得分:0)

这是一个简单的解决方案:

var textstring = "Dear < EmployeeList >, kindly complete your joining documentation and submit the same to < DepartmentList > latest by < DateCalendar >";

textstring.replace("< EmployeeList >", "ABC");
textstring.replace("< DepartmentList >", "DepHr");
textstring.replace("< DateCalendar >", "12 March");