2

The Example

Red Color Or Black Color

if i would replace or string with and using this code

var k = "Red Color Or Black Color";
var s = k.replace("or","and");
alert(s);

The Result : Red Coland and Black Coland

I Want To Replace or Only ..

1
  • 1
    What is the problem? You can use k.replace(/\sor\s/i," and ") Commented Mar 28, 2015 at 16:18

1 Answer 1

4

If you want to replace insensitively, make use of regex and use ignoreCase(i) flag also use word-boundaries. The string version replaces only the first occurrence and is case-sensitive.

If you want to replace all "or" regardless of their case, add g to the regex.

var k = "Red Color Or Black Color";
var s = k.replace(/\bor\b/gi,"and");
alert(s);
Sign up to request clarification or add additional context in comments.

4 Comments

@KarimMamdouh check now.
Oh Sorry I Forget To Use ignoreCase + Global .. anyway thanks it working greatly :D
@KarimMamdouh why would you do that? It returns the index, which isn't what's needed.
i'm using jQuery too .. for example $(document).ready(function() { $('textarea').keyup(function() { var val = this.value; if ( this.value.indexOf("wrong") !== -1 ) { this.value = this.value.replace("wrong","right");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.