Home >Web Front-end >Front-end Q&A >How to implement regular replacement in jquery

How to implement regular replacement in jquery

青灯夜游
青灯夜游Original
2022-03-28 15:40:262890browse

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');".

How to implement regular replacement in jquery

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!

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