Home Web Front-end JS Tutorial JS method to replace spaces in string_javascript skills

JS method to replace spaces in string_javascript skills

May 16, 2016 pm 04:03 PM

复制代码 代码如下:


通常情况下输入域当中的 替换不掉(源代码当中有 ,页面上显示为空格),如果想替换掉,可以用另外手段。
增加一个隐藏域,值为 ,然后再替换

复制代码 代码如下:

var sp=document.getElementById("space").value;
strData = document.all( "CommDN").value;
strData=strData.replace(sp,"");

js代码

复制代码 代码如下:

function formatStr(str)
{
str=str.replace(/\r\n/ig,"
");
return str;
}

要注意两点:

要使用正则表达式,不能使用 str.replace("\r\n", newString); ,这会导致只替换第一个匹配的子字符串。
母字符串中不一定 \r\n 会同时存在,也许只有 \n,没有 \r 也是可能的。

replace方法的语法是:stringObj.replace(rgExp, replaceText) 其中stringObj是字符串(string),reExp可以是正则表达式对象(RegExp)也可以是字符串(string),replaceText是替代查找到的字符串。。为了帮助大家更好的理解,下面举个简单例子说明一下

Js代码

<script language="javascript"> 
var stringObj="终古人民共和国,终古人民"; 
//替换错别字“终古”为“中国” 
//并返回替换后的新字符 
//原字符串stringObj的值没有改变 
var newstr=stringObj.replace("终古","中国"); 
alert(newstr); 
</script>  

Copy after login

比我聪明的你,看完上面的例子之后,会发现第二个错别字“终古”并没有被替换成“中国”,我们可以执行二次replace方法把第二个错别字“终古”也替换掉,程序经过改进之后如下:

Js代码

<script language="javascript"> 
var stringObj="终古人民共和国,终古人民"; 
//替换错别字“终古”为“中国” 
//并返回替换后的新字符 
//原字符串stringObj的值没有改变 
var newstr=stringObj.replace("终古","中国"); 
newstr=newstr.replace("终古","中国"); 
alert(newstr); 
</script>
Copy after login

我们可以仔细的想一下,如果有N的N次方个错别字,是不是也要执行N的N次方replace方法来替换掉错别字呢??呵,不用怕,有了正则表达式之后不用一个错别字要执行一次replace方法。。程序经过改进之后的代码如下

Js代码

<script language="javascript"> 
var reg=new RegExp("终古","g"); //创建正则RegExp对象 
var stringObj="终古人民共和国,终古人民"; 
var newstr=stringObj.replace(reg,"中国"); 
alert(newstr); 
</script> 
Copy after login

上面讲的是replace方法最简单的应用,不知道大家有没有看懂??下面开始讲稍微复杂一点的应用。。 大家在一些网站上搜索文章的时候,会发现这么一个现象,就是搜索的关键字会高亮改变颜色显示出来??这是怎么实现的呢??其实我们可以用正则表达式来实现,具体怎么样实现呢?简单的原理请看下面的代码

Js代码

<script language="javascript"> 
var str="中华人民共和国,中华人民共和国"; 
var newstr=str.replace(/(人)/g,"<font color=red>$1</font>"); 
document.write(newstr); 
</script> 
Copy after login

上面的程序缺少互动性,我们再改进一下程序,实现可以自主输入要查找的字符

Js代码

<script language="javascript"> 
var s=prompt("请输入在查找的字符","人"); 
var reg=new RegExp("("+s+")","g"); 
var str="中华人民共和国,中华人民共和国"; 
var newstr=str.replace(reg,"<font color=red>$1</font>"); 
document.write(newstr); 
</script> 
Copy after login

可能大家都会对$1这个特殊字符表示什么意思不是很理解,其实$1表示的就是左边表达式中括号内的字符,即第一个子匹配,同理可得$2表示第二个子匹配。。什么是子匹配呢??通俗点讲,就是左边每一个括号是第一个字匹配,第二个括号是第二个子匹配。。 当我们要把查找到的字符进行运算的时候,怎么样实现呢??在实现之前,我们先讲一下怎么样获取某一个函数的参数。。在函数Function的内部,有一个arguments集合,这个集合存储了当前函数的所有参数,通过arguments可以获取到函数的所有参数,为了大家理解,请看下面的代码

Js代码

<script language="javascript"> 
function test(){ 
 alert("参数个数:"+arguments.length); 
 alert("每一个参数的值:"+arguments[0]); 
 alert("第二个参数的值"+arguments[1]); 
 //可以用for循环读取所有的参数 
} 
 
test("aa","bb","cc"); 
</script> 

Copy after login

看懂上面的程序之后,我们再来看下面一个有趣的程序

Js代码

<script language="javascript"> 
var reg=new RegExp("\\d","g"); 
var str="abd1afa4sdf"; 
str.replace(reg,function(){alert(arguments.length);}); 
</script>  

Copy after login

我们惊奇的发现,匿名函数竟然被执行了二次,并且在函数里还带有三个参数,为什么会执行二次呢??这个很容易想到,因为我们写的正则表达式是匹配单个数字的,而被检测的字符串刚好也有二个数字,故匿名函数被执行了二次。。在匿名函数内部的那三个参数到底是什么内容呢??为了弄清这个问题,我们看下面的代码。

Js代码

<script language="javascript"> 
function test(){ 
for(var i=0;i<arguments.length;i++){ 
 alert("第"+(i+1)+"个参数的值:"+arguments); 
} 
} 
var reg=new RegExp("\\d","g"); 
var str="abd1afa4sdf"; 
str.replace(reg,test); 
</script>  
Copy after login

经过观察我们发现,第一个参数表示匹配到的字符,第二个参数表示匹配时的字符最小索引位置(RegExp.index),第三个参数表示被匹配的字符串(RegExp.input)。其实这些参数的个数,还会随着子匹配的变多而变多的。弄清这些问题之后,我们可以用另外的一种写法

Js代码

<script language="javascript"> 
function test($1){ 
 return "<font color='red'>"+$1+"</font>" 
} 
var s=prompt("请输入在查找的字符","人"); 
var reg=new RegExp("("+s+")","g"); 
var str="中华人民共和国,中华人民共和国"; 
var newstr=str.replace(reg,test); 
document.write(newstr); 
</script> 
Copy after login

看了上面的程序,原来可以对匹配到的字符为所欲为。下面简单举一个应用的例子

Js代码

<script language="javascript"> 
var str="他今年22岁,她今年20岁,他的爸爸今年45岁,她的爸爸今年44岁,一共有4人" 
function test($1){ 
 var gyear=(new Date()).getYear()-parseInt($1)+1; 
 return $1+"("+gyear+"年出生)"; 
} 
var reg=new RegExp("(\\d+)岁","g"); 
var newstr=str.replace(reg,test); 
alert(str); 
alert(newstr); 
</script>
Copy after login

以上所述就是本文的全部内容了,希望大家能够喜欢。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do I create and publish my own JavaScript libraries? How do I create and publish my own JavaScript libraries? Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

How do I optimize JavaScript code for performance in the browser? How do I optimize JavaScript code for performance in the browser? Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

How do I debug JavaScript code effectively using browser developer tools? How do I debug JavaScript code effectively using browser developer tools? Mar 18, 2025 pm 03:16 PM

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

How do I use Java's collections framework effectively? How do I use Java's collections framework effectively? Mar 13, 2025 pm 12:28 PM

This article explores effective use of Java's Collections Framework. It emphasizes choosing appropriate collections (List, Set, Map, Queue) based on data structure, performance needs, and thread safety. Optimizing collection usage through efficient

How do I use source maps to debug minified JavaScript code? How do I use source maps to debug minified JavaScript code? Mar 18, 2025 pm 03:17 PM

The article explains how to use source maps to debug minified JavaScript by mapping it back to the original code. It discusses enabling source maps, setting breakpoints, and using tools like Chrome DevTools and Webpack.

Getting Started With Chart.js: Pie, Doughnut, and Bubble Charts Getting Started With Chart.js: Pie, Doughnut, and Bubble Charts Mar 15, 2025 am 09:19 AM

This tutorial will explain how to create pie, ring, and bubble charts using Chart.js. Previously, we have learned four chart types of Chart.js: line chart and bar chart (tutorial 2), as well as radar chart and polar region chart (tutorial 3). Create pie and ring charts Pie charts and ring charts are ideal for showing the proportions of a whole that is divided into different parts. For example, a pie chart can be used to show the percentage of male lions, female lions and young lions in a safari, or the percentage of votes that different candidates receive in the election. Pie charts are only suitable for comparing single parameters or datasets. It should be noted that the pie chart cannot draw entities with zero value because the angle of the fan in the pie chart depends on the numerical size of the data point. This means any entity with zero proportion

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

See all articles