Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
71 views
in Technique[技术] by (71.8m points)

javascript - Replace method doesn't work

I want to replace the smart quotes like , , and to regular quotes. Also, I wanted to replace the ?, ? and ?. I used the following code. But it doesn't help. Kindly help me to resolve this issue.

str.replace(/[“”]/g, '"');
str.replace(/[‘’]/g, "'");
question from:https://stackoverflow.com/questions/65557872/cant-replace-n-by-n-in-a-string-in-typescript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use:

str = str.replace(/[“”]/g, '"');
str = str.replace(/[‘’]/g, "'");

or to do it in one statement:

str = str.replace(/[“”]/g, '"').replace(/[‘’]/g,"'");

In JavaScript (as in many other languages) strings are immutable - string "replacement" methods actually just return the new string instead of modifying the string in place.

The MDN JavaScript reference entry for replace states:

Returns a new string with some or all matches of a pattern replaced by a replacement.

This method does not change the String object it is called on. It simply returns a new string.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...