Javascript 为什么赢了';当测试执行时,是否不能用我的正则表达式对象替换工作?
问这个问题我觉得很傻,因为我打赌答案就在我眼前,但事情就是这样 我正在从CSS样式的文本装饰中提取一个字符串,并试图删除该字符串的下划线部分(及其周围的任何空格)。当我运行test()时,它返回true,但当我执行replace方法时,字符串不变。帮忙 我的代码:Javascript 为什么赢了';当测试执行时,是否不能用我的正则表达式对象替换工作?,javascript,regex,Javascript,Regex,问这个问题我觉得很傻,因为我打赌答案就在我眼前,但事情就是这样 我正在从CSS样式的文本装饰中提取一个字符串,并试图删除该字符串的下划线部分(及其周围的任何空格)。当我运行test()时,它返回true,但当我执行replace方法时,字符串不变。帮忙 我的代码: textDecoration = function(str) { var n_str = str + '|/\s' + str + '|/\s' + str + '/\s|' + str + '/\s'
textDecoration = function(str) {
var n_str = str + '|/\s' + str + '|/\s' + str + '/\s|' + str + '/\s';
var nre = new RegExp(n_str, "g");
debug_log('Found or not: ' + nre.test(txt));
txt.replace(nre, '');
debug_log('Result: ' + txt);
debug_log('-----------------------');
}
var txt = "underline";
debug_log('-----------------------');
debug_log('Starting String: ' + txt);
textDecoration("underline");
txt = "underline overline line-through";
debug_log('-----------------------');
debug_log('Starting String: ' + txt);
textDecoration("underline");
txt = "overline underline line-through";
debug_log('-----------------------');
debug_log('Starting String: ' + txt);
textDecoration("underline");
txt = "overline line-through underline";
debug_log('-----------------------');
debug_log('Starting String: ' + txt);
textDecoration("underline");
输出:
replace()
返回一个带有替换的新字符串,不更改实际字符串。你应该这样做:
var newString = txt.replace(nre, '');
debug_log('Result: ' + newString);
replace()。你应该这样做:
var newString = txt.replace(nre, '');
debug_log('Result: ' + newString);
test
返回一个布尔值<代码>替换
返回一个新字符串。它不会改变字符串
而且,您的正则表达式非常奇怪。应用str=“underline”
,您将获得:
/underline|\/sunderline|\/sunderline\/s|underline\/s/
它不匹配空格,但返回布尔值<代码>替换返回一个新字符串。它不会改变字符串 而且,您的正则表达式非常奇怪。应用
str=“underline”
,您将获得:
/underline|\/sunderline|\/sunderline\/s|underline\/s/
它不匹配空格,但是我对regex是新手。我假设它将匹配“下划线”、“下划线”、“下划线”和“下划线”。我错了吗?在你给RegExp构造函数的字符串中,s被转义(到s),在它前面有一个斜杠。您需要在字符串中的s之前转义反斜杠,使其成为regexp的空白元字符。此外,您不应该删除“下划线”两侧的空格:-)哦,不要同时删除两个空格,这是个好主意!如果是中间那我就有麻烦了。我会做更多的搜索,找出如何正确地逃离这些。非常感谢你的帮助!我对regex不熟悉。我假设它将匹配“下划线”、“下划线”、“下划线”和“下划线”。我错了吗?在你给RegExp构造函数的字符串中,s被转义(到s),在它前面有一个斜杠。您需要在字符串中的s之前转义反斜杠,使其成为regexp的空白元字符。此外,您不应该删除“下划线”两侧的空格:-)哦,不要同时删除两个空格,这是个好主意!如果是中间那我就有麻烦了。我会做更多的搜索,找出如何正确地逃离这些。非常感谢你的帮助!