【发布时间】:2011-07-11 08:41:05
【问题描述】:
我喜欢替换 JavaScript 中所有不以 < 或 / 开头的字符串。我能够匹配单词,但我只想替换单词,而不是前面的字符。
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);
我得到结果[" body", "xbody"]
如果我使用replace() 而不是match() 我将用替换字符串替换“body”和“xbody”。但我只想用替换字符串替换“body”。该怎么做?
更多解释:
使用替换:
var testResult5 = testHtmlStr.replace(re5, "HELLO");
console.log(testResult5);
替换后的结果字符串:
"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"
替换函数将body 替换为HELLO,但我想替换body(前面没有空格)。还将xbody 替换为HELLO,但我只想替换body 而不是xbody。
希望这更清楚。
【问题讨论】:
标签: javascript regex string