例如我有这个字符串:
var string = 'attr:clase';
var new_string = string.replace(":clase",":class");
所以输出是:
>> new_string = 'attr:class';
好吧,到目前为止一切都很好,但我有一个问题,如果我有这个字符串会发生什么:
var string = 'attr:claseStatus';
var new_string = string.replace(":clase",":class");
我现在的输出是:
>> new_string = 'attr:classStatus';
但我不想要它,我想要这个输出:
>> new_string = 'attr:claseStatus';
我的意思是,如果有确切的名称,我只需要更改,但如果我的字符串有一些附加文本不更改,它就像区分大小写吗?或者不敏感,我不确定,我希望你能帮助我,谢谢:S
--------已编辑----------
我不得不说“:clase”是一个字符串,所以如果你能告诉我如何将它更改为reg表达式将会非常有用,谢谢大家:
x = ':clase';
y = somefunction(x);
y = /:clase$/; //for example
最佳答案
如何使用正则表达式并检查词尾
var new_string = string.replace(/:clase\b/,":class");
正则表达式中的 \b
代表单词结尾,因此它将采用 :clase ,但不采用 :claseSomething
关于Javascript 仅当完全相同时才替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33691894/