javascript 如何使用jquery替换字符串中的字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14732416/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 22:26:36  来源:igfitidea点击:

How to replace a character from a string using jquery?

javascriptjquery

提问by vin

How to replace charecter "/" to "-" from string using jquery.

如何使用jquery将字符串中的字符“/”替换为“-”。

I want as below:

我想要如下:

06/01/2013 to 06-01-2013

In My Case:

在我的情况下:

I am taking a value from input box

我从输入框中取值

<input id="from-date" value="06/01/2013" name="from-date"/>

fdate = $("#from-date").val();
fdate.replace('/','-');
console.log(fdate);

but it return same string(06/01/2013).

但它返回相同string(06/01/2013)

回答by Denys Séguret

You don't need jQuery but the standard replace function with the proper regex syntax :

您不需要 jQuery,但需要具有正确正则表达式语法的标准替换函数:

fdate = fdate.replace(/\//g, '-');

Note that replacedoesn't change the string you pass but returns a new one. Note also you need to pass the gflag so that all occurrences are replaced.

请注意,replace这不会更改您传递的字符串,而是返回一个新字符串。另请注意,您需要传递g标志,以便替换所有出现的内容。