简体   繁体   English

如何用Javascript中的replace()替换多个字符串

[英]How to replace multiple strings with replace() in Javascript

I'm guessing this is a simple problem, but I'm just learning... 我猜这是一个简单的问题,但我只是在学习......

I have this: 我有这个:

var location = (jQuery.url.attr("host"))+(jQuery.url.attr("path"));
locationClean = location.replace('/',' ');

locationArray = locationClean.split(" ");

console.log(location);
console.log(locationClean);
console.log(locationArray);

And here is what I am getting in Firebug: 这是我在Firebug中获得的内容:

stormink.net/discussed/the-ideas-behind-my-redesign
stormink.net discussed/the-ideas-behind-my-redesign
["stormink.net", "discussed/the-ideas-behind-my-redesign"]

So for some reason, the replace is only happening once? 所以出于某种原因,替换只发生过一次? Do I need to use Regex instead with "/g" to make it repeat? 我是否需要使用正则表达式而不是“/ g”来重复? And if so, how would I specifiy a '/' in Regex? 如果是这样,我如何在Regex中指定'/'? (I understand very little of how to use Regex). (我对如何使用Regex知之甚少)。

Thanks all. 谢谢大家。

使用模式而不是字符串,可以将其与“global”修饰符一起使用

locationClean = location.replace(/\//g,' ');

The replace method only replaces the first occurance when you use a string as the first parameter. 当您使用字符串作为第一个参数时,replace方法仅替换第一次出现。 You have to use a regular expression to replace all occurances: 您必须使用正则表达式来替换所有出现:

locationClean = location.replace(/\//g,' ');

(As the slash characters are used to delimit the regular expression literal, you need to escape the slash inside the excpression with a backslash.) (由于斜杠字符用于分隔正则表达式文字,因此需要使用反斜杠转义表达式中的斜杠。)

Still, why are you not just splitting on the '/' character instead? 不过,为什么你不只是拆分“/”字符呢?

You could directly split using the / character as the separator: 您可以使用/字符作为分隔符直接拆分

var loc =  location.host + location.pathname, // loc variable used for tesing
    locationArray = loc.split("/");

This can be fixed from your javascript. 这可以从您的JavaScript修复。

SYNTAX 句法

stringObject.replace(findstring,newstring)

findstring: Required. findstring:必需。 Specifies a string value to find. 指定要查找的字符串值。 To perform a global search add a 'g' flag to this parameter and to perform a case-insensitive search add an 'i' flag. 要执行全局搜索,请在此参数中添加“g”标志,并执行不区分大小写的搜索添加“i”标记。

newstring: Required. newstring:必填。 Specifies the string to replace the found value from findstring 指定要从findstring中替换找到的值的字符串

Here's what ur code shud look like: 这是你的代码shud看起来像:

locationClean = location.replace(new RegExp('/','g'),' ');
locationArray = locationClean.split(" ");

njoi' njoi”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM