Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to replace first occurence of match in javascript

I have below test cases as input:

  1. [This is my test] [This is my test] My name is xyz.

    Want Expected output as :
    [This is my test] My name is xyz.
    .

  2. [This is my test] My name is xyz.
    Want Expected output as:
    My name is xyz.

For above test cases I want to replace only first occurrence of '[This is my test] ' with blank. I don't want to replace second occurrence of match.

How do I resolve this using regex in JavaScript?

Thanks in advance.

ETA:

I just want to give more clarification that, i dont want to use hard coded value in regex , i want to use variable in regex.
Assume that [This is my test] is stored in one variable i.e. var defaultMsg = "[This is my test] ";

like image 881
pravin Avatar asked Jan 22 '23 18:01

pravin


1 Answers

Anyone try this?

<script>
var defaultMsg ="[This is my test]"
var str         = "[This is my test] [This is my test] My name is xyz.";
str=str.replace(defaultMsg,"");
alert(str);
</script>

No need for regexp and replace does not care about special chars if the source string is not a regular expression object but just a string. Tested Mozilla 1.7, FF3.6.6, Safari 5, Opera 10 and IE8 windows XP sp3. Not sure I understand why this was voted down if it does the job with a minimum of fuss.

to replace all occurrences, add a g (note: this is not standard):

str=str.replace(defaultMsg,"","g"); // "gi" for case insensitivity 

replace MDN

like image 94
mplungjan Avatar answered Feb 05 '23 11:02

mplungjan