---
title: "JavaScript正则表达式：匹配位置"
author: "coding1688"
date: "2013-02-08T08:57:16Z"
tags: []
categories: ["Web前端"]
slug: "javascript"
draft: false
lastmod: "2013-02-08T09:02:14Z"
id: 1797456
url: "https://coding1688.iteye.com/blog/1797456"
---

在JavaScript正则表达式中，匹配开头、结尾、单词开始、单词结尾等有特殊的表示方法，列举如下：

匹配位置语法 描述 n$ 匹配任何结尾为 n 的字符串。 ^n 匹配任何开头为 n 的字符串。 ?=n 匹配任何其后紧接指定字符串 n 的字符串。 ?!n 匹配任何其后没有紧接指定字符串 n 的字符串。 \\b 查找位于单词的开头或结尾的匹配。 \\B 查找不处在单词的开头或结尾的匹配。

 

**示例1：对字符串结尾的 "is" 进行全局搜索。**

```
var str="Is this his";
var patt1=/is$/g;
document.write(str.match(patt1));
```

执行结果：

```
is
```

**示例2：对字符串开头的 "is" 进行全局搜索。**

```
var str="Is this his";
var patt1=/^Is/g;
document.write(str.match(patt1));
```

执行结果：

```
Is
```

**示例3：对其后紧跟 "all" 的 "is" 进行全局搜索。**

```
var str="Is this all there is";
var patt1=/is(?= all)/;
document.write(str.match(patt1));
```

执行结果：

```
is
```

**示例4：对其后没有紧跟 "all" 的 "is" 进行全局搜索。**

```
var str="Is this all there is";
var patt1=/is(?! all)/gi;
document.write(str.match(patt1));
```

执行结果：

```
Is,is
```

**示例5：对字符串中的单词的开头或结尾进行 "W3" 的全局搜索。**

```
var str="Visit W3School"; 
var patt1=/\bW3/g;
document.write(str.match(patt1));
```

执行结果：

```
W3
```

**示例6：对字符串中不位于单词开头或结尾的 "School" 进行全局搜索。**

```
var str="Visit W3School"; 
var patt1=/\BSchool/g;
document.write(str.match(patt1));
```

执行结果：

```
School
```

 

- 源文【JavaScript正则表达式：匹配位置】最新版，请访问：  
     [http://www.vktone.com/articles/js-regexp-position.html](http://www.vktone.com/articles/js-regexp-position.html)
- 更多关于【正则表达式】的文章，请访问：  
     [http://www.vktone.com/tags/regexp.html](http://www.vktone.com/tags/regexp.html)