在javascript中替换' ' [英] replace ' ' in javascript

查看:27
本文介绍了在javascript中替换' '的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下方法在 JavaScript 中进行替换:

I'm trying to do replace in JavaScript using:

r = "I
am
here";
s = r.replace("
"," ");

但不是给我

我来了

作为s的值,它返回相同的内容.

as the value of s, It returns the same.

问题出在哪里??

推荐答案

正如其他人所说,您的正则表达式缺少全局标志.正确的表达应该是别人给你的.

As stated by the others the global flag is missing for your regular expression. The correct expression should be some thing like what the others gave you.

var r = "I
am
here";
var s = r.replace(/
/g,' ');

我想指出与从一开始发生的事情的不同之处.您使用了以下语句

I would like to point out the difference from what was going on from the start. you were using the following statements

var r = "I
am
here";
var s = r.replace("
"," ");

这些陈述确实是正确的,将替换字符 的一个实例.它使用不同的算法.当给出要替换的字符串时,它将查找第一次出现并简单地将其替换为作为第二个参数给出的字符串.使用正则表达式时,我们不仅要查找要匹配的字符,还可以编写复杂的匹配语法,如果找到一个或多个匹配项,则将替换它.有关 JavaScript 正则表达式的更多信息,请参见 w3schools.

The statements are indeed correct and will replace one instance of the character . It uses a different algorithm. When giving a String to replace it will look for the first occurrence and simply replace it with the string given as second argument. When using regular expressions we are not just looking for the character to match we can write complicated matching syntax and if a match or several are found then it will be replaced. More on regular expressions for JavaScript can be found here w3schools.

例如,您创建的方法可以更通用,以解析来自几种不同类型文件的输入.由于操作系统的差异,在需要换行的地方有带有 或 的文件是很常见的.为了能够同时处理您的代码,可以使用正则表达式的某些功能进行重写.

For instance the method you made could be made more general to parse input from several different types of files. Due to differences in Operating system it is quite common to have files with or where a new line is required. To be able to handle both your code could be rewritten using some features of regular expressions.

var r = "I
am
here";
var s = r.replace(/[

]/g,' ');

这篇关于在javascript中替换' '的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆