Jump to content

Recommended Posts

Im trying to replace words in a string, I can do it like this..

 

var output = "hello bob";
output = output.replace(/hello/g, "goodbye");

 

But when I try using variables, I cant get it to work :/

 

var output = "hello bob";

var replace = new Array();
var replace_with = new Array();

replace[0] = "hello"; replace_with[0] = "goodbye";

output = output.replace("/" + replace[0] + "/g", replace_with[0]);

 

Link to comment
https://forums.phpfreaks.com/topic/215144-replace-using-variables/
Share on other sites

Below is a working example. Also, I would add the word boundry to the expression ("\b", but need to use "\\b" to escape the backslash). Otherwise, if you were replacing "car" with "auto" and the word "cartoon" existed in your output, you would end up with "autotoon".

 

<html>
<head>
<script type='text/javascript'>

function replaceWord()
{
    //Get input values
    var searchWord  = document.getElementById('search').value;
    var replaceWord = document.getElementById('replace').value;
    var inputText   = document.getElementById('input').value;
    
    //Create reg ex expression and perform replacement
    var replaceRegEx = new RegExp('\\b'+searchWord+'\\b', 'g');
    var outputText = inputText.replace(replaceRegEx, replaceWord);
    document.getElementById('output').value = outputText;
}

</script>
</head>
<body>

Input:<br />
<textarea id="input" style="width:400px;height:100px;">The quick brown fox jumped over the lazy dog</textarea>
<br /><br />

Output:<br />
<textarea id="output" style="width:400px;height:100px;" disabled="disabled"></textarea>
<br /><br />

Search Word: <input type="text" id="search" value="quick" /><br />
Replace Word: <input type="text" id="replace" value="slow" />

<br /><br />
<button onclick="replaceWord();">Replace</button>
</body>
</html>

basically javascript's .replace() method accepts either a string or regex object as the first argument.  If you try to do what you did, you end up just passing a string to it, and it tries to match the whole thing as a literal string. 

 

You can pass the actual (delimited) pattern (and optional modifiers) as an object and it will treat it as an anonymous regex object like so:

 

.replace(/pattern/g,'') 

 

 

But if you want to use variables in your pattern, you must do as mjdamato has shown and take the extra step of creating an actual regex object, where the pattern is a string argument, and you can therefore throw variables into the mix.

No offense intended, but you stated you have been "too busy" to even look at the help you ask for, but it is also apparent you have also been "too busy" to even do a basic "javascript replace" google search and see that these questions you are asking are basic and come up quite often and are quite easy to find the answers to. 

 

We don't care about how "busy" you are, because we are volunteering our time and knowledge to help you out.  If you cannot bother to take the time out of your "busy" schedule for free help, or at least show some level of courtesy beyond "I can't be bothered with this, just gimme it," then perhaps you should look in to hiring someone to do it for you.  We are here to help and guide you through a learning process, not spoon-feed you or do your work for free. 

No offense intended, but you stated you have been "too busy" to even look at the help you ask for...

 

Well, I do take offense. The example I provided was a complete, customizable working example. Just copy/paste the code into an HTML document and you caould have verified that the code does replace all instances of the search word. And THAT was based upon the initial code you provided which used the "g" paramater to make the replacements "global".

 

No offense intended, but you stated you have been "too busy" to even look at the help you ask for...

 

Well, I do take offense. The example I provided was a complete, customizable working example. Just copy/paste the code into an HTML document and you caould have verified that the code does replace all instances of the search word. And THAT was based upon the initial code you provided which used the "g" paramater to make the replacements "global".

 

 

Exactly my point.  "Too busy" to even bother looking at what was already spoon-fed to him. 

Thanks for that guys, I had to travel 250 miles to attend my grandfathers funeral in London. Not everything is what you make it out to be. Now I am back I thank you for all your help, but in future please don't think I'm being arrogant.

Thanks for that guys, I had to travel 250 miles to attend my grandfathers funeral in London. Not everything is what you make it out to be. Now I am back I thank you for all your help, but in future please don't think I'm being arrogant.

 

 

Or, perhaps you should be more aware of how you word things and how they might come across as.  All we can do is take what you say at face value.  At face value you said you were too busy to look at stuff and proceeded to ask another question that would have easily been answered if you had looked at what was given or even done a basic google search in general.

 

Sorry for your loss, but I have to agree with CV. I'm also curious as to why you did have time to post a reply and ask an additional question about something that apparently wasn't important to you at the time.

 

I really don't care about an answer, just thinking out loud. In any event, you have your solution and you've at least said "thank you" (which is more than many people do these days). So, I have all I need from this thread.

Thats working fine, but when I try to change a smiley such as ":)", it breaks, I have tried different things like the following but none work, what am I doing wrong?

 

var searchWord  = "";
var searchWord  = "\:\)";
var searchWord  = "/\:\)/";

 

Cant quite understand this, the code below is what I am trying to attempt

 

 

var input = document.getElementById('input').value;var searchWord = new Array();var replaceWord = new Array();searchWord[0] = ""; replaceWord[0] = "smiley image";var replaceRegEx = new RegExp('\\b' + searchWord[0] + '\\b', 'g');input = input.replace(replaceRegEx, replaceWord[0]);alert(input);

 

 

I stated previously that the regex code for a word boundry was "\b", but that you would need to add a second backslash to escape the first backslash. So....

 

If you need to escape another character (such as the ":" or ")") then the same logic would apply - wouldn't it?

searchWord[0] = "\\:\\)";

 

I'm pretty sure you only need to escape the paren and not the colon, but it doesn't hurt to escape them both.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.