开发者

Replace a word only if it's not preceded by a certain character(s)

I like to replace all occurrences of a string in JavaScript where the strin开发者_StackOverflowg does not start with < or /. I was able to match the word but I want to replace the word only, not the preceding characters.

var hitName1 = "body";

var testHtmlStr = "This is a test string with <body> html tag and with regular body string and another <body> html string and with no flexbody and with /body as in a url string";

var re5 = new RegExp('[^<\/]' + hitName1 , 'gi');

console.log(re5);

var testResult5 = testHtmlStr.match(re5);

console.log(testResult5);

I get the result [" body", "xbody"]

If I use replace() instead of match() I will replace " body" and "xbody" with replace string. But I would like to replace only "body" with replace string. How to do that?

More explanation:

use of replace:

var testResult5 = testHtmlStr.replace(re5, "HELLO");

console.log(testResult5);

The resulting string after replacement:

"This is a test string with <body> html tag and with regularHELLO string and another <body> html string and with no fleHELLO and with /body as in a url string"

The replace function replaced body with HELLO, but I want to replace body (with nospace infront). Also the xbody replaced with HELLO, but I want to replace only body not xbody.

Hope this is more clear.


One way you could do it is defining a capturing group around the preceding character:

var hitName1='body';
var testHtmlStr = "This is a test string with <body> html tag and with regular body string and another <body> html string and with no flexbody and with /body as in a url string";
var re5 = new RegExp('([^<\/]|^)' + hitName1, 'gi');

alert(testHtmlStr.replace(re5, '$1'));

jsFiddle Demo

So if you want to replace your string with fos for example, you can write $1fos.

UPDATE: Following @yankee's comment I've changed the regex: added |^ to make it work when testHtmlStr starts with hitName1 or is equal to it.


well i couldn't understand what you want to do exactly but i think you are trying to replace some tags from a string that contains tags and other textNodes

However, i think if you use "for" loop to verify which tags should be replace and which tags shouldn't, you will be able to do what you need.

for(result in testResult5)
{
    if(result!="body") {// do what you want}
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜