简体   繁体   English

JavaScript正则表达式未按预期替换

[英]JavaScript Regex not replacing as expected

I have this function in PHP: 我在PHP中具有以下功能:

function sanitizeKey($str){
  $str = strtolower($str);
  $str = preg_replace('/[^\da-z ]/i', '', trim(ucwords($str)));
  $str = str_replace(" ", "", $str);
  $str = lcfirst($str);
  return $str;
}

When run against Manufacture's P/N the output is manufacturesPn . Manufacture's P/N ,输出为manufacturesPn

I'm rewriting the same function in Javascript and so far have this code: 我正在用Javascript重写相同的函数,到目前为止有以下代码:

str = "Manufacture's  P/N";

str = str.toLowerCase()
  .replace(/\b[a-z]/g, function(letter) { // php's ucwords
    return letter.toUpperCase();
  });
str = str.trim(); // remove leading & trailing whitespace
str = str.replace("/[^\da-z ]/i", ''); // keep alphanumeric
str = str.replace(/\s+/g, ''); // remove whitespace
str = str.replace(/\b[a-z]/g, function(letter) { // php's lcfirst
  return letter.toLowerCase();
});

console.log(str);

At this point if I input Manufacture's P/N the current output is Manufacture'SP/N . 在这一点上,如果我输入Manufacture's P/N则当前输出为Manufacture'SP/N

Question How do I change my JavaScript code to replicate the PHP program so it produces the same output for the same input? 问题如何更改我的JavaScript代码以复制PHP程序,以便它为相同的输入产生相同的输出?

You can use: 您可以使用:

 str = "Manufacture's P/N"; console.log( str.trim() .toLowerCase() .replace(/[^\\da-z ]+/gi, '') .replace(/(?!^)\\b[az]/g, function(c) { return c.toUpperCase(); }) .replace(/\\s+/g, '') ) //=> "manufacturesPn" 

In Javascript you shouldn't quote regex eg "/[^\\da-z ]/i" and use global flag to replace globally. 在Javascript中,您不应引用正则表达式,例如"/[^\\da-z ]/i"而应使用global标志全局替换。

You can match every character use .test() , .indexOf() within .replace() function 您可以在.replace()函数中使用.test() .indexOf()匹配每个字符

 var str = "Manufacture's P/N"; var res = str.replace(/./g, function(p) { return /[az]/i.test(p) && !/\\s/.test(str[str.indexOf(p) - 1]) ? p.toLowerCase() : /['/ ]/.test(p) ? "" : p }); console.log(res); 

Please try this. 请尝试这个。

str = "Manufacture's  P/N";

str = $.trim(str).split("  ");
str1 = str[0].toLowerCase().replace("'", '');
str2 = str[1].toLowerCase().replace("/", '');
str3 = str2.charAt(0).toUpperCase() + str2.slice(1);
finalString = str1 + str3;

return finalString;

console.log(finalString);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM