javascript - 正则表达式替换单个或多个连字符

标签 javascript regex

我编写了下面的函数来用连字符或反向转换空格

  1. 带连字符的空格 str.trim().replace(/\s+/g, '-')
  2. 带空格的连字符 str.replace(/\-/g,' ')

但现在我尝试用双连字符替换单连字符,我无法使用点 1 函数,因为它转换单个/多个出现而不是单个。

有没有办法编写在单个公式中执行 3 个操作的正则表达式

  1. 将正斜杠转换为下划线replace(/\//g, '_')
  2. 用单个连字符转换空格
  3. 将单个连字符转换为多个连字符

例如 正则表达式 1 处更改

"Name/Er-Gourav Mukhija" into "Name_Er--Gourav-Mukhija"

正则表达式 2 做相反的事情。

最佳答案

您可以使用回调函数而不是替换字符串。这样您就可以一次指定和替换所有字符。

const input = 'Name/Er-Gourav Mukhija';
const translate = {
  '/': '_',
  '-': '--',
  ' ': '-',
};
const reverse = {
  '_': '/',
  '--': '-',
  '-': ' ',
};

// This is just a helper function that takes
// the input string, the regex and the object
// to translate snippets.
function replaceWithObject( input, regex, translationObj ) {
  return input.replace( regex, function( match ) {
    return translationObj[ match ] ? translationObj[ match ] : match;
  } );
}

function convertString( input ) {
  // Search for /, - and spaces
  return replaceWithObject( input, /(\/|\-|\s)/g, translate );
}

function reverseConvertedString( input ) {
  // Search for _, -- and - (the order here is very important!)
  return replaceWithObject( input, /(_|\-\-|\-)/g, reverse );
}

const result = convertString( input );
console.log( result );
console.log( reverseConvertedString( result ) );

关于javascript - 正则表达式替换单个或多个连字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46694660/

相关文章:

asp.net - 使用 JavaScript 更改 ASP.NET 标签的可见性

JavaScript - 通过引用传递对象

regex - 如果元素以数字开头,则不要选择结尾数字

c# - Regex 可以用于这个特定的字符串操作吗?

javascript - 为 JavaScript 对象动态创建实例字段

javascript - 使用 Canvas 和 HTML5 创建类似 Flash 的动画

javascript - FireFox 滚动条

python - 几个类似的正则表达式。更快的方法来做到这一点?

java - 将 PCRE 正则表达式修改为 C# 或 Java 支持的正则表达式

regex - 这个正则表达式是如何工作的?