亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

js替換字符串中所有指定的字符(實(shí)現(xiàn)代碼)

 更新時間:2016年08月17日 11:18:33   投稿:jingxian  
下面小編就為大家?guī)硪黄猨s替換字符串中所有指定的字符(實(shí)現(xiàn)代碼)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

第一次發(fā)現(xiàn)JavaScript中replace() 方法如果直接用str.replace("-","!") 只會替換第一個匹配的字符.
而str.replace(/\-/g,"!")則可以全部替換掉匹配的字符(g為全局標(biāo)志)。

replace()

The replace() method returns the string that results when you replace text matching its first argument
(a regular expression) with the text of the second argument (a string).
If the g (global) flag is not set in the regular expression declaration, this method replaces only the first
occurrence of the pattern. For example,

var  s = "Hello. Regexps are fun." ;s = s.replace(/\./, "!" ); // replace first period with an exclamation pointalert(s);

produces the string “Hello! Regexps are fun.” Including the g flag will cause the interpreter to
perform a global replace, finding and replacing every matching substring. For example,

var  s = "Hello. Regexps are fun." ;s = s.replace(/\./g, "!" ); // replace all periods with exclamation pointsalert(s);

yields this result: “Hello! Regexps are fun!”

所以可以用以下幾種方式:

string.replace(/reallyDo/g, replaceWith);

string.replace(new RegExp(reallyDo, 'g'), replaceWith);

string:字符串表達(dá)式包含要替代的子字符串。
reallyDo:被搜索的子字符串。

replaceWith:用于替換的子字符串。

Js代碼

<script type="text/javascript"> 
String.prototype.replaceAll = function(reallyDo, replaceWith, ignoreCase) { 
  if (!RegExp.prototype.isPrototypeOf(reallyDo)) { 
    return this.replace(new RegExp(reallyDo, (ignoreCase ? "gi": "g")), replaceWith); 
  } else { 
    return this.replace(reallyDo, replaceWith); 
  } 
} 
</script> 

以上這篇js替換字符串中所有指定的字符(實(shí)現(xiàn)代碼)就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • JavaScript中reduce()的5個基本用法示例

    JavaScript中reduce()的5個基本用法示例

    這篇文章主要給大家介紹了關(guān)于JavaScript中reduce()的5個基本用法示例,文中通過示例代碼以及圖文介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用js具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-07-07
  • uniapp小程序的圖片(視頻)上傳的組件封裝方法

    uniapp小程序的圖片(視頻)上傳的組件封裝方法

    這篇文章主要介紹了uniapp做小程序的圖片(視頻)上傳的組件封裝,要求實(shí)現(xiàn)多張圖片的上傳 ,可以限制圖片上傳的數(shù)量,圖片預(yù)覽,多次使用對圖片的上傳順序排序,需要的朋友可以參考下
    2024-02-02
  • 使用Microsoft Ajax Minifier減小JavaScript文件大小的方法

    使用Microsoft Ajax Minifier減小JavaScript文件大小的方法

    大家用來減小JavaScript文件下載大小的常見的方式有2種: 壓縮(compression)和縮?。╩inification)。
    2010-04-04
  • 最新評論