I have this function in 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
.
I'm rewriting the same function in Javascript and so far have this code:
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
.
Question How do I change my JavaScript code to replicate the PHP program so it produces the same output for the same input?
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.
You can match every character use .test()
, .indexOf()
within .replace()
function
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.