正则表达式

标签 javascript regex replace

目前我在 javascript 中有一个基本的正则表达式,用于用分号替换字符串中的所有空格。字符串中的某些字符包含引号。理想情况下,我想用分号替换空格,但引号内的空格除外。

var stringin = "\"james johnson\" joe \"wendy johnson\" tony";
var stringout = stringin.replace(/\s+/g, ":");
alert(stringout);

谢谢 罗宾

最佳答案

尝试这样的事情:

var stringin = "\"james johnson\" joe \"wendy johnson\" tony";
var stringout = stringin.replace(/\s+(?=([^"]*"[^"]*")*[^"]*$)/g, ":");

请注意,当您的字符串中存在转义引号时,它会中断:

"ab \" cd" ef "gh ij"

关于正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1680217/

相关文章:

javascript - 功能子组件不会在 props 更改时重新渲染

javascript - 如何将 EMAIL 域自动附加到输入字段

mysql - 查找https:\/\/and replace with http:\/\/using phpMyAdmin

php - 在 PHP 中编译正则表达式

正则表达式搜索并替换为 Perl 中的变量

SQL Server : REPLACE function replace ' ' with ',' in string

javascript - 从另一个组件切换状态

javascript - js - match() 未正确返回值

javascript - 正则表达式 - 仅匹配数字,不包括特殊字符 - 不起作用

css - 字符串搜索替换 AS3