[removed]Replacing a but not the a in ab

2020-07-25 00:54发布

I was wondering if it was possible to replace certain strings but not others that contain the same value in javascript. For example, say I had the text A AB and wanted to replace only the standalone A but not the A in AB. (Note: I know that I could do this manually in this case, but I plan on using scenarios like this throughout large blocks of text) Is there an algorithm or built in js command for doing this?

4条回答
劳资没心,怎么记你
2楼-- · 2020-07-25 01:32

You can achieve this using regular expressions in javascript,

string = string.replace(/A/, "AB")

will replace the charecters which occurs for the first time.

string = string.replace(/A/g, "AB")

will replace the all occurances of "A" with "AB"

查看更多
【Aperson】
3楼-- · 2020-07-25 01:43

in addition to others answers, you could also write: string=string.replace(/a(?=\s)/,""); (?= means it will replace 'a' only if the next characers are space/tab, etc.. you could also write different regex instead of \s if you need other condition (only the 'a' will match ,not the condition regex in the (?=...)

for your other question in the comment(in Asaph answer)you can write:

str = str.replace(RegExp("\\b"+x+"\\b",'g'),'');

查看更多
我命由我不由天
4楼-- · 2020-07-25 01:50

If you wish to replace just the stand-alone letter "A", then you may want something like:

var re = /(^|\s)a(\s|$)/ig;

Then you can do:

var s = 'A ab a ba a-b b-a a:v b a';
alert(s.replace(re, 'Z')); // ZabZba a-b b-a a:v bZ

Note that this also removes white space arounding the letter.

Edit

To keep whitespace:

alert( s.replace(re, '$1Z$2') ); // Z ab Z ba a-b b-a a:v b Z
查看更多
放荡不羁爱自由
5楼-- · 2020-07-25 01:56

Use a regular expression with word boundaries.

var str = 'A AB';
str = str.replace(/\bA\b/g, '');
查看更多
登录 后发表回答