How to change regex pattern from textbox? [duplicate] - javascript

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!

Related

Javascript .innerHTML fuction output only flashes

I have written a JS code to find if a string is palindrome or not. But the output only stays on for less than a second then disappears.
I know this type of question has been asked before and I tried the solution which said to add "return false" but its not working for me.
function palindrome(str) {
var str1 = str.split("");
var str2 = str1.reverse();
var str3 = str2.join("");
return str3;
}
function checkpalin() {
var x = document.getElementById("pform").value;
var st = palindrome(x);
var flag = st.localeCompare(x);
if (flag === 0)
document.getElementById('demo').innerHTML = "Given number is a palindrome";
else
document.getElementById('demo').innerHTML = "Not palindrome";
return false;
}
<form>
Please enter a string:<br>
<input type="text" name="str" id="pform" onchange="return checkpalin()"><br>
</form>
<p id="demo"></p>
It's because you have it in a form. Try this
function palindrome(str) {
var str1 = str.split("");
var str2 = str1.reverse();
var str3 = str2.join("");
return str3;
}
function checkpalin() {
var x = document.getElementById("pform").value;
var st = palindrome(x);
var flag = st.localeCompare(x);
if (flag === 0)
document.getElementById('demo').innerHTML = "Given number is a palindrome";
else
document.getElementById('demo').innerHTML = "Not palindrome";
return false;
}
<!DOCTYPE html>
<html>
<body>
Please enter a string:<br>
<input type="text" name="str" id="pform" onchange="return checkpalin()"><br>
<p id="demo"></p>
</body>
</html>
You can also use oninput instead of onchange to make it update while you are typing in the textbox.
function palindrome(str) {
var str1 = str.split("");
var str2 = str1.reverse();
var str3 = str2.join("");
return str3;
}
function checkpalin() {
var x = document.getElementById("pform").value;
var st = palindrome(x);
var flag = st.localeCompare(x);
if (flag === 0)
document.getElementById('demo').innerHTML = "Given number is a palindrome";
else
document.getElementById('demo').innerHTML = "Not palindrome";
return false;
}
<!DOCTYPE html>
<html>
<body>
Please enter a string:<br>
<input type="text" name="str" id="pform" oninput="return checkpalin()"><br>
<p id="demo"></p>
</body>
</html>
The default event when hitting enter in a single field in a form is to submit the form.
In your code the return is only interesting on the submit event.
Just preventDefault on the submit or remove the form tags
function palindrome(str) {
var str1 = str.split("");
var str2 = str1.reverse();
var str3 = str2.join("");
return str3;
}
document.getElementById("myForm").onsubmit = function(e) {
e.preventDefault();
var x = document.getElementById("pform").value;
var st = palindrome(x);
var flag = st.localeCompare(x);
document.getElementById('demo').innerHTML = flag ? "Not palindrome" : "Given string is a palindrome";
}
<form id="myForm">
Please enter a string and hit enter:<br>
<input type="text" name="str" id="pform"><br>
</form>
<p id="demo"></p>

javascript - split on plus and minus

How do I split a var, which I got from a text input on a "+", "-", "x" and "^"?
JavaScript
function integralinput() {
var a = document.getElementById("input").value;
console.log(a);
var b = a.split("x" + "^" + "+" + "-");
console.log(b);
}
html:
<input id="input" type="text"><label for="function">Funktion</label>
<input type="button" onclick="integralinput()" value="Run">
Use a regex
var b = a.split(/[x^+-]/)
If you want only number you can use like this
function integralinput() {
var a = document.getElementById("input").value;
var b = a.match(/\d+/g).map(Number);
console.log(b);
}
<input value="10+20-3x5^6" id="input" type="text"><label for="function">Funktion</label>
<input type="button" onclick="integralinput()" value="Run">

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>

replace all occurrences in string using 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);

How to append array elements to div?

I have been trying to change so I get the push from a input form but having no luck.
<form id="myform">
<input id="type" type="text" name="input">
<button onclick="myFunction()">Add number</button>
</form>
<br>
<div id="box"; style="border:1px solid black;width:150px;height:150px;overflow:auto">
</div>
<script>
var number= [];
function myFunction()
{
number.push= document.getElementById("type").value;
var x=document.getElementById("box");
x.innerHTML=number.join('<br/>');
}
</script>
Replace:
var x = document.getElementById("demo");
With:
var x = document.getElementById("box");
And if you want to convert your array into string, you can use the javascript function join():
x.innerHTML = number.join(',');
// Or
x.innerHTML = number.toString();
Is this what you want?
You need to convert array, like:
x.innerHTML=number.join(",");
And:
var x = document.getElementById("box");
var arr = [];
function func () {
arr.push('5');
document.getElementById('box').innerHTML = arr.toString();
}

Categories