替换第一个出现的字符串

时间:2016-10-14 04:48:09

标签: javascript jquery regex

我有一个字符串变量如下:

id | complete | submitdate

请注意,该值分别由survay_name | active | cratedate 分隔,并且val不是固定/硬编码的。 我如何每次只更换bVal?

2 个答案:

答案 0 :(得分:1)

修改

如果使用string作为正则表达式,请转义该字符串以防止恶意攻击:

$.ajax({
    type: 'GET',
    url: '/url/goes/here',
    dataType: "json",
    success: function(data) {
       $('.user').each(function(key, value){ //i need to remove .user and use data-user here (if possible)
            $(value).find('.userid').text(data[key].id); //i need to put values using data attr instead of find
            $(value).find('.usernm').text(data[key].name); //i need to put values using data attr instead of find              
       });
    }
});



RegExp.escape = function(string) {
  return string.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
}; 

new RegExp(RegExp.escape(string));




答案 1 :(得分:1)

试试这个

    <!doctype html>
<head>
<title>JavaScript Game</title>
<style>
#container {
height:400px;
width:600px;
outline: 1px solid black;
position:absolute;
left:50px;
top: 0px;
background-color:green;
}
#guy {
position:absolute;
height:50px;
width:50px;
outline: 1px solid black;
background-color:red;
left: 200px;
top: 200px;
}
</style>
</head>
<body>

<div id="container"></div>
<div id="guy"></div>
<script>
var guy=document.getElementById("guy");
var cont=document.getElementById("container");
var lastX,lastY; // Tracks the last observed mouse X and Y position


guy.addEventListener("mousedown", function(event) {
    if (event.which == 1) {
      lastX = event.pageX;
      lastY = event.pageY;
      addEventListener("mousemove", moved);
      event.preventDefault(); // Prevent selection
    }
  });

function buttonPressed(event) {
    if (event.buttons == null)
      return event.which != 0;
    else
      return event.buttons != 0;
  }
  function moved(event) {
    if (!buttonPressed(event)) {
      removeEventListener("mousemove", moved);
    } else {
      var distX = event.pageX - lastX;
      var distY = event.pageY - lastY;    
      guy.style.left =guy.offsetLeft + distX  + "px";
      guy.style.top = guy.offsetTop + distY  + "px";
      lastX = event.pageX;
      lastY = event.pageY;
    }
  }

</script>
</body>