js替换字符串中的单引号
时间: 2024-06-12 08:09:59 浏览: 11
可以使用正则表达式和replace方法来替换字符串中的单引号,代码如下:
```
let str = "I'm a string with 'single quotes'";
let newStr = str.replace(/'/g, "\\'");
console.log(newStr); // "I\\'m a string with \\'single quotes\\'"
```
相关问题
JS 去除字符串中的单引号
可以使用 JavaScript 中的 replace() 方法来去除字符串中的单引号。例如:
```javascript
let str = "She's a girl.";
str = str.replace(/'/g, "");
console.log(str); // 输出:She s a girl.
```
在上面的例子中,我们使用了正则表达式 /'/g 来匹配字符串中所有的单引号,并将其替换为空字符串。注意,在正则表达式中,单引号需要用反斜杠转义。
js 对象转字符串为单引号
可以使用 JSON.stringify() 方法将 JavaScript 对象转换为字符串,并在参数中传入一个函数,将字符串中的双引号替换为单引号。示例代码如下:
```
let obj = {name: 'John', age: 30};
let str = JSON.stringify(obj, function(key, value) {
if (typeof value === 'string') {
return value.replace(/"/g, "'");
}
return value;
});
console.log(str); // 输出:{"name":'John',"age":30}
```
这样就可以将字符串中的双引号替换为单引号了。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)