replace() 方法

目录

 

 

replace()

定义

replace() 方法用于在字符串中用一些字符替换另外一些字符,或替换一个与正则表达式匹配的子串。javascript

返回值

一个新的字符串,是用 replacement 替换了 regexp 的第一次匹配或全部匹配以后获得的。css

说明

字符串 stringObject 的 replace() 方法执行的是查找并替换的操做。它将在 stringObject 中查找与 regexp 相匹配的子字符串,而后用 replacement 来替换这些子串。若是 regexp 具备全局标志 g,那么 replace() 方法将替换全部匹配的子串。不然,它只替换第一个匹配子串。html

例子

// css 替换字符串 为 javascript
var str="html css"
console.log(str.replace(/css/, "javascript"))
//html javascriptvue

 

// 全局替换 css 替换字符串 为 javascript
str = str + 'vue css is that one two css'
console.log(str.replace(/css/g, "javascript"))
//html javascriptvue javascript is that one two javascriptjava

 

// 匹配字符串大写字符的正确
text="html javascript css"
console.log(text.replace(/javascript/i, "JavaScript"))
//html JavaScript css正则表达式

 

// 把 "Doe, John" 转换为 "John Doe" 的形式
name = "Doe, John";
console.log(name.replace(/(\w+)\s*, \s*(\w+)/, "$2 $1"))
//John Doeurl

 

// 将把全部的花引号替换为直引号
stringName = '"a", "b"';
console.log(stringName.replace(/"([^"]*)"/g, "'$1'"))
//'a', 'b'spa

 

// 将把字符串中全部单词的首字母都转换为大写
name = 'aaa bbb ccc';
uw=name.replace(/\b\w+\b/g, function(word){
return word.substring(0,1).toUpperCase()+word.substring(1);}
);
console.log(uw)
//Aaa Bbb Ccccode

strname.replace("\r\n","<br/>") //匹配字符换行regexp

 

匹配字符串中空格

去除字符串内全部的空格:str = str.replace(/\s*/g,"");

去除字符串内两头的空格:str = str.replace(/^\s*|\s*$/g,"");

去除字符串内左侧的空格:str = str.replace(/^\s*/,"");

去除字符串内右侧的空格:str = str.replace(/(\s*$)/g,"");

匹配字符串中逗号

去除字符串中全部的逗号:str = str.replace(/,/g, "");

去除字符串中最后的逗号:str = str.replace(/,$/gi,"");

 

匹配字符串中特殊字符

//你要清除的符号都放在方括号里,记得要用斜杠\转义一下,否则会出错

str = str.replace(/[要清除的符号]/g,'')

var url = 'https://baidu.com/bai/7788'

//去掉/和//console.log(url.replace(/[//]/g,'')) //https:baidu.combai7788//去掉/和//console.log(url.replace(/\//g,'')) //https:baidu.combai7788//去掉冒号console.log(url.replace(/\:/g,'')) //https//baidu.com/bai/7788//去掉点console.log(url.replace(/\./g,'')) //https://baiducom/bai/7788

相关文章
相关标签/搜索