replace all occurrences in string using javascript - javascript

I have this string:
"dsfnsdfksh[aa]lkdfjldfjgljd[aa]"
I need to find all occurrencies of [aa] and replace it by another string, for example: dd
How can I do that?

You can use a regex with the g flag. Note that you will have to escape the [ and ] with \
//somewhere at the top of the script
if (!RegExp.escape) {
RegExp.escape = function(value) {
return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&")
};
}
var string = "dsfnsdfksh[aa]lkdfjldfjgljd[aa]";
var pattern = '[aa]';
var regex = new RegExp(RegExp.escape(pattern), 'g');
var text = string.replace(regex, 'dd');
console.log(text)

You can use .replace for this. Here is an example:
HTML
<!DOCTYPE Html />
<html>
<head>
<title></title>
</head>
<body>
<input type="text" id="theInput" />
<input type="submit" value="replace" id="btnReplace"/>
<script type="text/javascript" src="theJS.js"></script>
</body>
</html>
JavaScript
var fieldInput = document.getElementById("theInput");
var theButton = document.getElementById("btnReplace");
theButton.onclick = function () {
var originalValue = fieldInput.value;
var resultValue = originalValue.replace(/\[aa\]/g, "REPLACEMENT");
fieldInput.value = resultValue;
}

With this I can replace all occurrencies:
var pattern = '[aa]';
var string = "dsfnsdfksh[aa]lkdfjldfjgljd[aa]";
var text = string.replace(new RegExp(pattern.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'g'), 'dd');
console.log(text);

Related

Find the word after specific word

i am new in javascript.
I have below code where textarea contains text as...
<textarea id="myBox" >
{Picker:} Helper
This is just demo...
</textarea>
<br/>
<span id="ans"></span> <br/>
<input type="button" onclick="getWord()" value="Click"/>
i am trying to find out the word exact after the {Picker:}, i.e. i want to find word "Helper". So word {Picker:} is the point from where i am starting to find immediate word after it. For this i using indexOf. What i did uptil now is ...
<script>
function getWord() {
var val = $("#myBox").val();
var myString = val.substr((val.indexOf("{Picker:}")) + parseInt(10), parseInt(val.indexOf(' ')) );
$("#ans").text(myString);
}
</script>
will anyone guide me to find what mistake i am making. Thanks in advance.
You should start from the index of "{Picker:}" + 9, because the length of the particular string is 9.
Parse till the the index of '\n' which is the line break character.
String.prototype.substr() is deprecated, use String.prototype.substring() instead.
function getWord() {
var val = $("#myBox").val();
var myString = val.substring((val.indexOf("{Picker:}")) + 9, val.indexOf('\n'));
$("#ans").text(myString);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<textarea id="myBox">
{Picker:} Helper
This is just demo...
</textarea>
<br />
<span id="ans"></span> <br />
<input type="button" onclick="getWord()" value="Click" />
var val = $("#myBox").val();
console.log(val)
var tempArray = val.replace("\n", " ").split(" ");
var wordToFind;
for(var i = 0 ; i < tempArray.length; i++) {
var word = tempArray[i];
if (word == "{Picker:}") {
wordToFind = tempArray[i + 1]
}
}
console.log(wordToFind)
This will assign what ever word comes after Picker: to the wordToFind variable.
Check working :https://jsfiddle.net/o5qasnd0/14/
You could do something like this
const text = "{Picker:} Helper";
const wordArr = text.split(' ');
const idx = wordArr.indexOf('{Picker:}');
console.log(idx != -1 && (idx + 1) < wordArr.length ? wordArr[idx + 1] : 'not found');

change color of words within an array

if i have an javascript array of words
var keywords = ["select","from","where","mars"];
and HTML element holding a text
<div id="mytext">Hello from planet mars</div>
How to use javascript to color in orange any word found in this element mytext of words list in the array keywords !
Here is one way to do it:
var keywords = ["select", "from", "where", "mars"];
let originalText = document.querySelector("#mytext").innerText
for (const word of keywords) {
originalText = originalText.replace(new RegExp(word, "g"), `<span class="orange">${word}</span>`)
}
document.querySelector("#mytext").innerHTML = originalText
.orange {
color: orange;
}
<div id="mytext">Hello from planet mars</div>
we are iterating over the keywords and replacing the innerHTML with a new content where we would wrap mentions of the keyword with a markup that would give it a color.
<html>
<head></head>
<body>
<div id="mytext">Hello from planet mars</div>
<script>
var keywords = ["select","from","where","mars"];
mytext=document.getElementById("mytext");
len=keywords.length;
for(i=0;i<len;i++){
mytext.innerHTML=mytext.innerHTML.replaceAll(keywords[i],"<span style='color:orange;'>"+ keywords[i] +"</span>");
}
</script>
<body>
You can use this code and replace the orange color with the color you want
var keywords = ["select","from","where","mars"];
mytext=document.getElementById("mytext");
len=keywords.length;
for(i=0;i<len;i++){
mytext.innerHTML=mytext.innerHTML.replaceAll(keywords[i],"<span style='color:orange;'>"+ keywords[i] +"</span>");
}
<html>
<head></head>
<body>
<div id="mytext">Hello from planet mars</div>
<body>
</html>
var keywords = ["select","from","where","mars"];
let div = document.getElementById('mytext')
let text_content = div.textContent.split(' ')
let html = text_content.map(e => {
return keywords.includes(e) ? `<span class='orange'>${e}</span>` : e })
div.innerHTML = html.join(' ')
.orange{
color:orange;
}
<div id="mytext">Hello from planet mars</div>
you can try
var keywords = ["select","from","where","mars"];
const el = document.querySelector('#mytext');
keywords.map(kw => el.innerText = el.innerText.replace(new RegExp(kw, 'g'), '<span style="color: oragne">' + kw + '</span>'))
el.innerHTML = el.innerText
Yet another regex option, but creating a single regex out of the array resulting in a single query/innerHTML assignment.
const keywords = ["select","from","where","mars"];
const mytext = document.getElementById('mytext');
mytext.innerHTML = mytext.textContent.replace(
new RegExp(`\\b${keywords.join('\\b|\\b')}\\b`, 'g'),
(match) => `<span class='orange'>${match}</span>`
);
.orange {
color: orange;
}
<div id="mytext">Hello from planet <span class="where">mars</span>, select from fromage mars.</div>
The resulting regex
/\bselect\b|\bfrom\b|\bwhere\b|\bmars\b/g

How to skip converting element text

i want output text oldnames not changes if user insert text 'false'
for example:
user input text "false toni" in textbox.
and i want output still "false toni"
why my code still changes text "toni" with "rina"?
<script type="text/javascript" charset="utf-8">
String.prototype.replaceArr = function(find, replace) {
var replaceString = this;
var regex;
for (var i = 0; i < find.length; i++) {
regex = new RegExp(find[i], "g");
replaceString = replaceString.replace(regex, replace[i]);
}
return replaceString;
}
function test() {
var x = document.getElementById("myText").value;
var oldNames = ['toni','rian'];
var newNames = ['rina','susi'];
if (oldNames== 'false ' + oldNames){
document.getElementById("check").innerHTML = x.replaceArr(oldNames, oldNames);
}else{
document.getElementById("check").innerHTML = x.replaceArr(oldNames, newNames);
}
}
</script>
<body>
ENTER TEXT: <br>
<textarea name="kata_cari" id="myText" style="width:100%; height:100px;"></textarea>
<br>
<input type="button" onclick="test();" value="Check!">
<br>
<p id="check"></p>
</body>
UPDATE:
Improve the question:
Trying enter text "My name is rian and my name is false toni" .
Posible to make output "rian" still change to "susi"?
use includes x.includes(value) to check whether the text area value contains a word that you want to replace . if it contains false then your oldnames not get changed.
If you are using IE then use x.indexOf(value)>0 instead of x.includes(value)
http://www.w3schools.com/jsref/jsref_includes.asp
<script type="text/javascript" charset="utf-8">
String.prototype.replaceArr = function(find, replace) {
var replaceString = this;
var regex;
for (var i = 0; i < find.length; i++) {
regex = new RegExp(find[i], "g");
replaceString = replaceString.replace(regex, replace);
}
return replaceString;
}
function test() {
var x = document.getElementById("myText").value;
var oldNames = ['toni', 'rian'];
var newNames = ['rina', 'susi'];
oldNames.forEach(function(value, index) {
/*if (x.includes('false '+value)){
var oldNames1=['false '+value];
x = x.replaceArr(oldNames1, oldNames1);
}*/
if (x.includes(value)) {
var oldNames1 = [value];
x = x.replaceArr(oldNames1, newNames[index]);
newNames1 = ['false ' + newNames[index]];
oldNames1 = ['false ' + value];
x = x.replaceArr(newNames1, oldNames1);
}
});
document.getElementById("check").innerHTML = x;
}
</script>
<body>
ENTER TEXT:
<br>
<textarea name="kata_cari" id="myText" style="width:100%; height:100px;"></textarea>
<br>
<input type="button" onclick="test();" value="Check!">
<br>
<p id="check"></p>
</body>
You false checking condition is wrong, you can do it using substr:
if (x.substr(0, 6) === 'false ') {
// The string starts with false
} else {
}
You can find more details on the substr from MDN.
UPDATE: As mentioned in the comment same can be done via startsWith and this is a better approach.
if (x.startsWith('false ')) {
// The string starts with false
} else {
}
try this. Compare array values instead of array.
<script type="text/javascript" charset="utf-8">
String.prototype.replaceArr = function(find, replace) {
var replaceString = this;
var regex;
for (var i = 0; i < find.length; i++) {
regex = new RegExp(find[i], "g");
replaceString = replaceString.replace(regex, replace[i]);
}
return replaceString;
}
function test() {
var x = document.getElementById("myText").value;
var oldNames = ['toni','rian'];
var newNames = ['rina','susi'];
if (x.indexOf('false') > -1 ){
document.getElementById("check").innerHTML = x.replaceArr(oldNames, oldNames);
}else{
document.getElementById("check").innerHTML = x.replaceArr(oldNames, newNames);
}
}
</script>
<body>
ENTER TEXT: <br>
<textarea name="kata_cari" id="myText" style="width:100%; height:100px;"></textarea>
<br>
<input type="button" onclick="test();" value="Check!">
<br>
<p id="check"></p>
</body>

Removing a range starting occurrence with specified place

I need to define the text area to delete from 4th occurrence of (_) and preserve the extension.
before 12_345_678_900_xxxxxxxxxxxxxxx.jpg after 12_345_678_900.jpg,
before 34_567_890_123_xxxxxxxx_xxxxx_xxxxxxxxxxx.jpg
after 34_567_890_123.jpg
Is it possible?
One solution is to find the nth occurence and then use substring.
var one='12_345_678_900_xxxxxxxxxxxxxxx.jpg'; // 12_345_678_900.jpg
function nth_occurrence (string, char, nth) {
var first_index = string.indexOf(char);
var length_up_to_first_index = first_index + 1;
if (nth == 1) {
return first_index;
} else {
var string_after_first_occurrence = string.slice(length_up_to_first_index);
var next_occurrence = nth_occurrence(string_after_first_occurrence, char, nth - 1);
if (next_occurrence === -1) {
return -1;
} else {
return length_up_to_first_index + next_occurrence;
}
}
}
console.log(one.substring(0,nth_occurrence(one,'_',4))+one.substring(one.indexOf('.')));
Sure, split by "_" and then join back the data you want:
var str = "12_345_678_900_xxxxxxxxxxxxxxx.jpg";
str = str.split("_").slice(0,4).join("_") + "."+ str.split(".").slice(-1)
console.log(str)
Regular Expressions are great for this sort of scenario:
const data1 = '12_345_678_900_xxxxxxxxxxxxxxx.jpg'
const data2 = '34_567_890_123_xxxxxxxx_xxxxx_xxxxxxxxxxx.jpg'
const re = /^([^_]+_[^_]+_[^_]+_[^_]+).*(.jpg)$/;
var test1 = data1.replace(re, '$1$2');
var test2 = data2.replace(re, '$1$2');
Try it out: https://jsfiddle.net/648xt3qq/
There are probably a few different regular expression approaches that would get the job done
Maybe this works for you:
function clean() {
var el = document.getElementById('area');
el.value = el.value.replace(/^(.*?_.*?_.*?_.*?)(_.*?)(\..*?.*)$/gmi, '$1$3');
}
<form action="">
<textarea cols="50" rows="4" id="area">12_345_678_900_xxxxxxxxxxxxxxx.jpg
34_567_890_123_xxxxxxxx_xxxxx_xxxxxxxxxxx.jpg</textarea><br />
<input type="submit" onclick="clean(); return false;" />
</form>

How to change regex pattern from textbox? [duplicate]

This question already has answers here:
Javascript Regexp dynamic generation from variables? [duplicate]
(4 answers)
Closed 7 years ago.
How I could set the variable pat to act as variable patt1? I want write in the textbox just "abe" and change from var patt1 = /\b[abc]+\b/g; to var patt1 = /\b[abe]+\b/g;. Is that possible?
<html>
<body onload="onload();">
<input type="text" id="lol"/>
<input type="button" VALUE="Resitve" onclick="myFunction();"/>
<p id="alert"></p>
<script>
var pat;
function myFunction() {
pat = document.getElementById("lol").value;
var str = "abc ab abe abeee";
var patt1 = /\b[abc]+\b/g;
var result = str.match(pat);
document.getElementById("alert").innerHTML = result;
}
</script>
</body>
</html>
You can use the RegExp object:
<html>
<body onload="onload();">
<input type="text" id="lol"/>
<input type="button" VALUE="Resitve" onclick="myFunction();"/>
<p id="alert"></p>
<script>
var pat;
function myFunction() {
pat = document.getElementById("lol").value;
var str = "abc ab abe abeee";
var patt1 = new RegExp("\\b[" + pat + "]+\\b","g");
var result = patt1.exec(str);
document.getElementById("alert").innerHTML = result;
}
</script>
</body>
</html>
Or you can simply make the pattern in your code as string:
<html>
<body onload="onload();">
<input type="text" id="lol"/>
<input type="button" VALUE="Resitve" onclick="myFunction();"/>
<p id="alert"></p>
<script>
var pat;
function myFunction() {
pat = document.getElementById("lol").value;
var str = "abc ab abe abeee";
var patt1 = "\\b[" + pat + "]+\\b";
var result = str.match(patt1);
document.getElementById("alert").innerHTML = result;
}
</script>
</body>
</html>
If you want to truly find all matches, you will need to call the exec function in a loop:
<html>
<body onload="onload();">
<input type="text" id="lol"/>
<input type="button" VALUE="Resitve" onclick="myFunction();"/>
<p id="alert"></p>
<script>
var pat;
function myFunction() {
pat = document.getElementById("lol").value;
var str = "abc ab abe abeee";
var patt1 = new RegExp("\\b[" + pat + "]+\\b","g");
var result;
var display = document.getElementById("alert");
display.innerHTML = "";
while(result = patt1.exec(str)){
display.innerHTML += result + "<br/>";
}
}
</script>
</body>
</html>
From the String.prototype.match() docs
str.match(regexp)
regexp
If a non-RegExp object obj is passed, it is implicitly converted to a
RegExp by using new RegExp(obj).
So, passing your regex as a concatenated string should work fine. i.e., instead of this:
var patt1 = /\b[abc]+\b/g;
Use this:
var patt1 = "/\b[abc]+\b/g";
And amend that string as you see fit!

Categories