JavaScript Regular Expression Replace Except First And Last
I want to write a regular expression in JavaScript . So string can be replaced but except first and last one. e.g. str=''Marys' Home'' I want regular expression in JavaScript so
Solution 1:
You can use this:
var str = "'Marys' Home'";
var result = str.replace(/(?!^)(')(?!$)/g, '\\$1');
//=> 'Marys\' Home'
RegEx Demo
Solution 2:
var str = "'Marys' Home'"
function replace(str, pattern, replacement) {
var firstIndex = str.indexOf(pattern)
, lastIndex = str.lastIndexOf(pattern)
, re = new RegExp(pattern, 'g')
if (firstIndex < lastIndex)
str = str.substr(firstIndex + pattern.length, lastIndex)
return str.replace(re, replacement)
}
console.log(replace(str, "'", "\'"))
Something like this you are looking for?
Post a Comment for "JavaScript Regular Expression Replace Except First And Last"