SYNCERのロゴ
アイキャッチ画像

String.prototype.replace() - 文字列を置換する

String.prototype.replace()は、文字列を置換するメソッドです。置換前の文字は文字列、または正規表現(RegExp)で指定できます。

概要

名前
replace
所属
String.prototype
仕様書
https://tc39.github.io/ecma262/#sec-string.prototype.replace

説明

String.prototype.replace ( searchValue, replaceValue )

第1引数(searchValue)には、対象の文字列を表す正規表現(RegExp)を指定して下さい。

第2引数(replaceValue)には、置換後の文字列を指定して下さい。

デモ

String.prototype.replace()のデモです。

<!-- このコードは編集できます。 -->

<!DOCTYPE html>
<html>
<head>
	<style>
body {
	white-space: pre-wrap ;
}
	</style>
</head>
<body>
<script>
/** try it! **/
var string = "SYNCERxSYNCER" ;

var a = string.replace( /(NC)/, "●" ) ;
var b = string.replace( /(NC)/g, "●" ) ;
var c = string.replace( /([a-z]+)/, "●" ) ;
var d = string.replace( "SYNCER", "●" ) ;
var e = string.replace( /([a-z]+)([A-Z]+)/, "●" ) ;
/** try it! **/

var results = { a:a, b:b, c:c, d:d, e:e, } ;

for( var name in results ) {
	console.log( name, results[name] ) ;
	document.body.appendChild( new Text( name + " = " + JSON.stringify( results[name] ) + "\n" ) ) ;
}
</script>
</body>
</html>

サポート状況

ChromeFirefoxSafariEdgeIEOperaiOS SafariAndroid
  • Twitterでシェア
  • Facebookでシェア
  • Google+でシェア
  • はてなブックマークでシェア
  • pocketに保存
  • LINEでシェア
更新履歴
2017年9月29日 (金)
コンテンツを公開しました。