Home >Web Front-end >Front-end Q&A >How to implement regular replacement in jquery
In jquery, you can use the replace() function to implement regular replacement. This function is used to perform find and replace operations. It can replace content that matches the regular expression. The syntax is "text to be replaced." Object.replace(regular expression,'replacement value');".
The operating environment of this tutorial: windows7 system, jquery1.10.2 version, Dell G3 computer.
In jquery, you can use the replace() function to implement regular replacement.
Example:
<input type="text" id="name" value="1,2,3,4"><br><br> <button>正则替换</button>
If you want to change all the commas of value in input
to "-", first use jQuery replace method:
$(document).ready(function() { $("button").click(function() { var value = $("#name").val(); var result = value.replace(',','-'); $("#name").val(result); }) });
The result is that only the first comma is replaced, that is:
1-2,3,4
jQuery does not provide the replaceAll method. At this time, you can use regular expressions to achieve it:
$(document).ready(function() { $("button").click(function() { var value = $("#name").val(); var reg = new RegExp(',','g');// g表示全局替换 var result = value.replace(reg,'-'); $("#name").val(result); }) });
The result is:
1-2-3-4
[Recommended learning: jQuery video tutorial, web front-end video]
The above is the detailed content of How to implement regular replacement in jquery. For more information, please follow other related articles on the PHP Chinese website!