[Javascript] How to use JavaScript's String.replace

In JavaScript, you can change the content of a string using the replace method. This method signature is overloaded with a bunch of different ways to do string replacement in JavaScript. This lesson covers the entire API (including an interestingDSL for the replacement string).

console.clear()

simpleStringReplace()
simpleRegexReplace()
globalRegexReplace()
regexReplaceGroup()
advancedRegexReplaceGroup()
simpleFunctionReplacer()
regexFunctionReplacerGroup()

console.log(‘Tests passed‘)

function simpleStringReplace() {
  var input = ‘Perl is the best programming language‘
  var expected = ‘JavaScript is the best programming language‘

  var result = input.replace(‘Perl‘, ‘JavaScript‘)
  expect(result).toEqual(expected)
}

function simpleRegexReplace() {
  var input = ‘My phone number is 123-555-3344‘
  var expected = ‘My phone number is xxx-xxx-xxxx‘

  var result = input.replace(/\d{3}-\d{3}-\d{4}/, ‘xxx-xxx-xxxx‘)
  expect(result).toEqual(expected)
}

function globalRegexReplace() {
  var input = ‘The basketball is round, and the basketball is bouncy‘
  var expected = ‘The soccerball is round, and the soccerball is bouncy‘

  var result = input.replace(/basketball/ig, ‘soccerball‘)
  expect(result).toEqual(expected)
}

function regexReplaceGroup() {
  var input = ‘Search with [Google](https://google.com), tweet with [Twitter](https://twitter.com)‘
  var expected = ‘Search with <a href="https://google.com">Google</a>, tweet with <a href="https://twitter.com">Twitter</a>‘

  var result = input.replace(/\[(.*?)\]\((.*?)\)/g, ‘<a href="$2">$1</a>‘)
  expect(result).toEqual(expected)
}

function advancedRegexReplaceGroup() {
  var input = ‘foobarbaz‘
  var expected = ‘foofoo-bar-$-bazbaz‘

  var result = input.replace(‘bar‘, ‘$`-$&-$$-$\‘‘)
  expect(result).toEqual(expected)
}

function simpleFunctionReplacer() {
  var input = ‘theAnswerToLifeTheUniverseAndEverything‘
  var expected = ‘the-answer-to-life-the-universe-and-everything‘

  var result = input.replace(/[A-Z]/g, upperToHyphenLower)
  expect(result).toEqual(expected)

  function upperToHyphenLower(match) {
    return ‘-‘ + match.toLowerCase();
  }
}

function regexFunctionReplacerGroup() {
  var input = ‘These are the replacer arguments‘
  var expected = ‘These are the replacer arguments: replacer, arguments, 14, These are the replacer arguments‘

  var result = input.replace(/(replacer) (arguments)/, replacer)

  expect(result).toEqual(expected)

  function replacer(match, group1, group2, offset, wholeString) {
    return match + ‘: ‘ + [group1, group2, offset, wholeString].join(‘, ‘)
  }
}

console.clear()

simpleStringReplace()
simpleRegexReplace()
globalRegexReplace()
regexReplaceGroup()
advancedRegexReplaceGroup()
simpleFunctionReplacer()
regexFunctionReplacerGroup()

console.log(‘Tests passed‘)

function simpleStringReplace() {
  var input = ‘Perl is the best programming language‘
  var expected = ‘JavaScript is the best programming language‘

  var result = input.replace(‘Perl‘, ‘JavaScript‘)
  expect(result).toEqual(expected)
}

function simpleRegexReplace() {
  var input = ‘My phone number is 123-555-3344‘
  var expected = ‘My phone number is xxx-xxx-xxxx‘

  var result = input.replace(/\d{3}-\d{3}-\d{4}/, ‘xxx-xxx-xxxx‘)
  expect(result).toEqual(expected)
}

function globalRegexReplace() {
  var input = ‘The basketball is round, and the basketball is bouncy‘
  var expected = ‘The soccerball is round, and the soccerball is bouncy‘

  var result = input.replace(/basketball/ig, ‘soccerball‘)
  expect(result).toEqual(expected)
}

function regexReplaceGroup() {
  var input = ‘Search with [Google](https://google.com), tweet with [Twitter](https://twitter.com)‘
  var expected = ‘Search with <a href="https://google.com">Google</a>, tweet with <a href="https://twitter.com">Twitter</a>‘

  var result = input.replace(/\[(.*?)\]\((.*?)\)/g, ‘<a href="$2">$1</a>‘)
  expect(result).toEqual(expected);

// $2 --> (.*?) --> (https://google.com)
// $1 --> [.*?] --> [Google]
}

function advancedRegexReplaceGroup() {
  var input = ‘foobarbaz‘
  var expected = ‘foofoo-bar-$-bazbaz‘

  var result = input.replace(‘bar‘, ‘$`-$&-$$-$\‘‘)
  expect(result).toEqual(expected)
}

function simpleFunctionReplacer() {
  var input = ‘theAnswerToLifeTheUniverseAndEverything‘
  var expected = ‘the-answer-to-life-the-universe-and-everything‘

  var result = input.replace(/[A-Z]/g, upperToHyphenLower)
  expect(result).toEqual(expected)

  function upperToHyphenLower(match) {
    return ‘-‘ + match.toLowerCase();
  }
}

function regexFunctionReplacerGroup() {
  var input = ‘These are the replacer arguments‘
  var expected = ‘These are the replacer arguments: replacer, arguments, 14, These are the replacer arguments‘

  var result = input.replace(/(replacer) (arguments)/, replacer)

  expect(result).toEqual(expected)

  function replacer(match, group1, group2, offset, wholeString) {
    return match + ‘: ‘ + [group1, group2, offset, wholeString].join(‘, ‘)
  }
}

[Javascript] How to use JavaScript's String.replace

时间: 2024-10-12 02:21:14

[Javascript] How to use JavaScript's String.replace的相关文章

JavaScript之基础-9 JavaScript String(内置对象、String概述)

一.JavaScript 内置对象 内置对象 - 什么是内置对象? 内置对象就是ECMAScript标准中已经定义好的,由浏览器厂商已经实现的标准对象 - 内置对象中封装了专门的数据和操作数据常用的API - JavaScript中内置对象列表 - String.Boolean.Number.Array.Date.RegExp.Math.Error.Function.Object.Global 包装类型 - 什么是包装类型? 专门封装原始类型的数据,并提供对数据常用操作的内置类型 - 为什么要用

javascript内置对象一:String

<script>    //string.split("-"),以字符"-"把string拆分成一个数组.返回一个数组    //array.join("-"),以字符"-"把数组array链接成一个字符串.    var str="welcome-to-school";    console.log(str.split("-"));//Array(3) [ "we

String.replace

replace方法是属于String对象的,可用于替换字符串. 简单介绍: String.replace(searchValue,replaceValue) String:字符串 searchValue:字符串或正则表达式 replaceValue:字符串或者函数 字符串替换字符串 'I am loser!'.replace('loser','hero') //I am hero! 直接使用字符串能让自己从loser变成hero,但是如果有2个loser就不能一起变成hero了. 'I am l

[转]String.Replace 和 String.ReplaceAll 的区别

JAVA 中的 replace replaceAll 问题: 测试code System.out.println("1234567890abcdef -----> "+"1234567890abcdef".replace("12345", "ABCDE"));  System.out.println("1234567890abcdef -----> "+"1234567890abcde

JavaScript 编程珠玑 - 《JavaScript: The good parts》总结(2)

一.扩展函数原型的更好办法: // 定义下面的通用方法 Function.prototype.method = function (name, func) {     this.prototype[name] = func;     return this; }; // 使用上面的通用方法作为工具进行扩展,以免每次扩展都访问Function.prototype.XXX (that's ugly). Number.method('integer', function() {     return 

js中字符替换函数String.replace()使用技巧

String.replace( ) 简介 语法: var strings = string.replace(regexp, replacement) regexp :您要执行替换操作的正则表达式,如果传入的是一个字符串,那就会当作普通字符来处理,并且只会执行一次替换操作:如果是正则表达式,并且带有 global (g) 修饰符,则会替换所有出现的目标字符,否则,将只执行一次替换操作. replacement :您要替换成的字符. 返回值是执行替换操作后的字符串. 11 String.replac

JAVA中string.replace()和string.replaceAll()的区别及用法

乍一看,字面上理解好像replace只替换第一个出现的字符(受javascript的影响),replaceall替换所有的字符,其实大不然,只是替换的用途不一样.    public String replace(char oldChar,char newChar)返回一个新的字符串,它是通过用 newChar 替换此字符串中出现的所有 oldChar 而生成的. 如 果 oldChar 在此 String 对象表示的字符序列中没有出现,则返回对此 String 对象的引用.否则,创建一个新的

JavaScript筑基篇(二)-&gt;JavaScript数据类型

说明 介绍JavaScript数据类型 目录 前言 参考来源 前置技术要求 JavaScript的6种数据类型 哪6种数据类型 undefined 类型 null 类型 boolean 类型 number 类型 string 类型 复杂 类型 基本型和引用型的不同 关于数据类型的一些常见疑问 为什么typeof null === 'object' string,String,object,Object,function,Function的关系 关于String类型与string类型的疑问 fun

如何选择Javascript模板引擎(javascript template engine)?

译者 jjfat 日期:2012-9-17  来源: GBin1.com 随着前端开发的密集度越来越高,Ajax和JSON的使用越来越频繁,大家肯定免不了在前台开发中大量的使用标签,常见到的例子如下: 你的到了一个JSON对象,如下: var data={   email: '[email protected],   gender: 'male'  } 然后你需要将json数据组织成页面内容,如下: var email, gender; email= '<div class="mail&q