JS regular replace search keyword highlighting effect
这次给大家带来JS的正则replace搜索关键字高亮效果,使用JS正则replace搜索关键字高亮效果的注意事项有哪些,下面就是实战案例,一起来看一下。
前言
正则表达式是字符串处理工具中强有力的工具.也有人认为这只是一个小玩具,但不管怎么说都离不开它.
这里介绍的是JavaScript的正则表达式的replace方法 ,和实现搜索关键字高亮的功能.
先介绍一下正则表达式的replace方法

JS regular replace search keyword highlighting effect
w3school原文链接介绍
正则表达式如何使用特殊字符$来表示原来的文本,这是实现搜索高亮的关键,
var str = "asad sad 123 sd qwe21"; str.replace(/\d+/img,"数字"); //这里正确的匹配到了数字,且替换成了中文的数字 console.log(str);//"asad sad 数字 sd qwe数字" ------------------------------------------------------ //看一下如何使用$1,表示被捕获的字符串 var str = "asad sad 123 sd qwe21"; str.replace(/\d+/img,"数字$1数字"); console.log(str);//"asad sad 数字$1数字 sd qwe数字$1数字" //很显然并没有成功,$1 还是$1,那么如何正确使用呢? ------------------------------------------------------ var str = "asad sad 123 sd qwe21"; str.replace(/(\d+)/img,"数字$1数字"); //这里就正确的匹配了数字并且用$1 表示原字符串并替换 console.log(str);///"asad sad 数字123数字 sd qwe数字21数字" /* ()在正则里面表示捕获性元组,可以用$1 特殊字符来表示被替换的内容,可以有多个()元组,也就是可以有多个$1,$2 */
开始小试身手
nbsp;html>
<style>
b{
color:red;
}
</style>
<p>
春江花月夜<br>
作者:张若虚<br>
春江潮水连海平,海上明月共潮生。 <br>
滟滟随波千万里,何处春江无月明! <br>
江流宛转绕芳甸,月照花林皆似霰; <br>
空里流霜不觉飞,汀上白沙看不见。 <br>
江天一色无纤尘,皎皎空中孤月轮。 <br>
江畔何人初见月?江月何年初照人? <br>
人生代代无穷已,江月年年只相似。 <br>
</p>
<input>
<script>
//input 输入要查找的字符串
input.onchange = function(){
//获取要查找的字符串
var searchVal = input.value;
// 获取要查找的内容
var text = poetry.innerHTML;
//将之前的查找高亮的字符串,取消高亮
text = text.replace(/<b[^>]*>([^>]*)<\/b[^>]*>/ig,"$1");
poetry.innerHTML = text;
//初始化正则表达式,加上括号(),形成可捕获元组.ig表示全局匹配和不区分大小写
var reg = new RegExp("("+searchVal +")","ig");
//高亮要查找的字符串
text = text.replace(reg,"<b>$1");
poetry.innerHTML = text;
}
</script>
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of JS regular replace search keyword highlighting effect. For more information, please follow other related articles on the PHP Chinese website!
Understanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AMUnderstanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.
Python vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AMPython is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.
Python vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AMPython and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.
From C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AMThe shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.
JavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AMDifferent JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.
Beyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AMJavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.
Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AMI built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing
How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AMThis article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Zend Studio 13.0.1
Powerful PHP integrated development environment

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 English version
Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.






