Small issue with String.Replace() - javascript

Not being too versed with JS yet, I've run into a weird issue where it seems like .replace() should be working but isn't.
I'm just trying to take a string (from an element ID) that has text + digits, replace the digits with a RegEx pattern, then replace the original text in that ID with the original text + new digits.
My HTML sample:
<html>
<body>
<p>Click the button to replace "Movies: 12344" with "Movies: 54321" in the paragraph below:</p>
<p id="demo">Movies: 1234!</p>
<button onclick="myFunction()">Try it</button>
</body>
</html>
My JS:
function myFunction() {
// Get all the text in #id=demo
var str = document.getElementById("demo");
// RegEx pattern to find ": <some digits>"
var pat = /\:\s?\d*/;
// Replace the digits
var res = str.replace(pat, ': 54321');
// Doesn't work (as a test) ...
//res = " hi"
// Replace the text in id=demo with original text + new digits.
str.innerHTML = res;
// Doesn't work (as a test) ...
//document.getElementById("demo").innerHTML = res;
}
At the moment, after clicking the button in the page, nothing happens.
This might help out a bit too:
https://codepen.io/stardogg/pen/aboREmL

In the same way you're setting the innerHTML in the last line of your function, innerHTML is also what you should be applying the replace on:
function myFunction() {
var str = document.getElementById("demo");
var pat = /\:\s?\d*/;
var res = str.innerHTML.replace(pat, ': 54321');
str.innerHTML = res;
}
<p>Click the button to replace "Movies: 12344" with "Movies: 54321" in the paragraph below:</p>
<p id="demo">Movies: 1234!</p>
<button onclick="myFunction()">Try it</button>

Your str variable is not equal to the text node within the element, but rather the element itself. To make str equal to the text within the element, try the following.
var str = document.getElementById("demo").innerText;

You need to extract text from the element before replacing.
//Replace the digits
var res = str.innerHTML.replace(pat, ': 54321');

Related

Why isn't "innerHTML" working when I try to insert onclick events on all the items of an array using the "forEach" method?

I am trying to get a text and add an onclick event with a function on each word of the text. It works perfectly with some sentences, but it doesn't with others. When it doesn't work, part of the html tags are displayed on the page. I noticed that it never works when there are repeated words or when I use the words "a" or "an", but I don't know why.
Here is how I am doing it:
I enter the text in the page using a textarea tag.
<textarea id="text-input"></textarea>
Then I grab the text, split it into an array with all the words and add an onclick event with a function to each word.
function addLink(){
let text = document.getElementById('text-input').value
const words = text.match(/\w+/g)
words.forEach(word => {
text = text.replace(word, `<span onclick=showWordDetail('${word}')>${word}</span>`)
})
document.getElementById('result').innerHTML = text
}
function showWordDetail(word){
let wordDetail = document.getElementById('word-detail')
result = `<h3>${word}</h3>`
return wordDetail.innerHTML = result
}
The "addLink" function is called when I submit the text.
<button onclick="addLink()">Submit</button>
If I enter, for example, "My brother is engineer". It works perfectly. The onclick event is added to all the words.
But if I enter "My brother is an engineer", this is the result:
"an onclick=showWordDetail('My')>My brother is an engineer."
I console.log'ed the array of all my attempts and the text is split correctly. So I have no idea why sometimes it works, but sometimes it doesn't.
I think this is what you want. It avoids some of the problems of the answers that just split at spaces.
const wordDetail = document.getElementById('word-detail'),
input = document.getElementById('text-input'),
result = document.getElementById('result');
function addLink() {
result.innerHTML = input.value.replace(/\w+/g,`<span onclick="showWordDetail('$&')">$&</span>`)
}
function showWordDetail(word) {
wordDetail.innerHTML = `<h3>${word}</h3>`
}
<textarea id="text-input"></textarea>
<button onclick="addLink()">Submit</button>
<div id="result"></div>
<hr/>
<div id="word-detail"></div>
My brother is an engineer
So this includes the word an.
Now look at what you replaced My with:
<span onclick=showWordDetail('My')>My</span>
So when you get to an what is going to be replaced?
What is the first place that the sequence of characters an attpears?
The an of the <span>
You would probably be better off with something like:
const html = words.map(word => `<span ....>${word}</span>`).join(" ");
document.getElementById('result').innerHTML = html
where you build a new set of HTML piece by piece instead of trying to replace the old content piece by piece.
Use split() instead, with separator space and replace every word, after replace it, add it to text value like that:
function addLink(){
let text = document.getElementById('text-input').value;
const words = text.split(" ");
text = "";
words.forEach(word => {
text += word.replace(word, `<span onclick=showWordDetail('${word}')>${word}</span> `);
});
document.getElementById('result').innerHTML = text;
}
function showWordDetail(word){
let wordDetail = document.getElementById('word-detail');
wordDetail.innerHTML = `<h3>${word}</h3>`;
}
<textarea id="text-input"></textarea>
<button onclick="addLink()">Submit</button>
<p id="result"></p>
<div id="word-detail"></div>

Remove white space inside single quotes before and after text inside the quotes

I am using a third-party plugin for javascript called QueryBuilder.
The problem is there is no way to trim the input after saved so the data is being saved like
testName=' test '
this is my javascript code, which is removing all spaces which is not what I want, I am trying to remove just space in the single quotes before and after all the text. Pretty much like a trim but the trim is not working so I need a regex to replace method
get_condition_sql__str = $.trim(get_condition_sql.sql);
get_condition_sql__clean = get_condition_sql__str.replace(/\s/g, '')
console.log(get_condition_sql__clean);
jQuery('.exception_conditions__sql').val(get_condition_sql__clean);
Lookahead for exactly one ' before the end of the string:
const input = `testName=' test '`;
const cleaned = input.replace(/ +(?=[^']*'$)/g, '');
console.log(cleaned);
There's only one word in the input, but if you need to preserve spaces between words inside the quotes, alternate between matching a ' on either side of spaces instead:
const input = `testName=' test test2 '`;
const cleaned = input.replace(/' +| +'/g, "'");
console.log(cleaned);
Please use this one for left space remove:
<script type="text/javascript">
var original_str3 = " This is a string"
//Strips all space to the left of the string
alert( original_str3.trimLeft() + ' <--- Without any spaces on the left' );
</script>
Or use this one for right space remove:
<script type="text/javascript">
var original_str4 = "This is a string "
//Strips all space to the right of the string
alert( original_str4.trimRight() + ' <--- Without any spaces on the right' );
For Remove space from both side character or string:
<script type="text/javascript">
var original_str2 = "S t r in g"
//Strips excessive white spaces i.e. retains only one space between each letter
var white_space_stripped_str = original_str2.replace(/\s+/g, ' ');
alert(white_space_stripped_str + ' <---- With exactly one space between each letter in case each letter has multiple spaces');
</script>
If any other are required then please let me know.
Example:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to replace "blue" with "red" in the paragraph below:</p>
<p id="demo">"vSourceCountry = 'TEST'"</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var str = `testName=' test test2 '`;
var res = str .replace(/' +| +'/g, "'");
document.getElementById("demo").innerHTML = res;
}
</script>
</body>
</html>
Result:
Click the button to replace "Microsoft" with "W3Schools" in the paragraph below:
testName='test test2'
Or You can use etc as per required:
https://www.w3schools.com/jsref/jsref_replace.asp

How to take the last character of string split using innerHTML

I'm trying to alert the last character of a string split, using innerHTML, but it's showing nothing in alert box.
this is my code
Html
<html>
<head>
<title>JavaScript basic animation</title>
<script type="text/javascript">
</script>
<script type="text/javascript" src="myfunction_2.js"></script>
</head> <body>
<div id="target">w3resource </div>
<button onclick="shubham()">click</button>
</body>
</html>
Function
function shubham()
{
var x=document.getElementById('target').innerHTML;
var y=x.split('');
var z=y[0];
var m=y[9];
var n=y[1]
var last=y[y.length-1]
alert(last);
}
it works properly if I take var x as
var x='w3resource';
but i need to take x value as
var x=document.getElementById('target').innerHTML;
so what should i do for this???
You need to use textContent instead of innerHTML. innerHTML gets you the actual HTML markup, including the tag angled brackets (<>), whereas textContent will give you just the text.
var x=document.getElementById('target').textContent.trim();
Your code code exactly what it should do - it alerts a last character of #target element (which is a whitespace in your case).
If you changed <div id="target">w3resource </div> to <div id="target">w3resource</div> (removed the space at the end) the result would be 'e'.
If you want to find the very last text character you would have to use:
function shubham() {
// Element reference
const element = document.getElementById('target');
// Text without spaces at the beggining and the end
const text = element.innerText.trim();
// Get the last character
const lastCharacter = text[text.length - 1];
// Alert the last character
alert(lastCharacter);
}
<div id="target">w3resource </div>
<button onclick="shubham()">click</button>
I see that you have a space in the target div:
<div id="target">w3resource </div>
Hence the last character is a blank space, remove all the blank space and it should work, use the function below :
function shubham3()
{
var x=document.getElementById('target').innerHTML.replace(/ /g,'');
var y=x.split('');
var z=y[0];
var m=y[9];
var n=y[1]
var last=y[y.length-1]
alert(last);
}

boundry condition with javascript regular expression

suppose if i have a string in javascript
var str=if {{SQL}}.Employee.name else {{SQL}}.EmployeeContact.phone
and want to replace {{SQL}}.Employee with {{SQL}}.Employee1
desired output is:
if {{SQL}}.Employee1.name else {{SQL}}.EmployeeContact.phone
but i am getting the output as below:
if {{SQL}}.Employee1.name else {{SQL}}.Employee1Contact.phone
below is the code for the same:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to replace "blue" with "red" in the paragraph below:</p>
<p id="demo">if {{SQL}}.EMPLOYEE.name else {{SQL}}.EMPLOYEECONTACT.phone</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var str = document.getElementById("demo").innerHTML;
var tr="{{SQL}}.EMPLOYEE"
var res = str.replace(new RegExp("\\b"+tr+"\\b","g"),"
{{SQL}}.EMPLOYEE1");
document.getElementById("demo").innerHTML = res;
}
</script>
</body>
</html>
The problem you're describing isn't the same as in your example code. The described problem is a missing word boundary. That is present in your code.
The problem in the code is that you have a word boundary before the expression as well. That's supposed to match the position between the space and the first {, and that doesn't qualify as a word boundary.
if {{SQL}}.EMPLOYEE
^^ - between these there's no word boundary since neither
space, nor the opening bracket are word characters.
Here's a working code sample with the first word boundary removed:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to replace "blue" with "red" in the paragraph below:</p>
<p id="demo">if {{SQL}}.EMPLOYEE.name else {{SQL}}.EMPLOYEECONTACT.phone</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var str = document.getElementById("demo").innerHTML;
var tr="{{SQL}}.EMPLOYEE";
var re = new RegExp( tr + "\\b","g");
var res = str.replace(re,"{{SQL}}.EMPLOYEE1");
document.getElementById("demo").innerHTML = res;
}
</script>
</body>
</html>
I've also escaped the period in the regex, since the unescaped . in the regex matches any character.

Replace HTML Comment along with string variable

In my project I have some html with comments surrounding text so I can find the text between particular comments and replace that text whilst leaving the comments so I can do it again.
I am having trouble getting the regex to work.
Here is an html line I am working on:
<td class="spaced" style="font-family: Garamond,Palatino,sans-serif;font-size: medium;padding-top: 10px;"><!--firstname-->Harrison<!--firstname--> <!--lastname-->Ford<!--lastname--> <span class="spacer"></span></td>
Now, here is the javascript/jquery that I have at the moment:
var thisval = $(this).val(); //gets replacement text from a text box
var thistoken = "firstname";
currentTemplate = $("#gentextCodeArea").text(); //fetch the text
var tokenstring = "<!--" + thistoken + "-->"
var pattern = new RegExp(tokenstring + '\\w+' + tokenstring,'i');
currentTemplate.replace(pattern, tokenstring + thisval + tokenstring);
$("#gentextCodeArea").text(currentTemplate); //put the new text back
I think I'm pretty close, but I don't have the regex right yet.
The regex ought to replace the firstname with whatever is entered in the textbox for $thisval (method is attached to keyup procedure on textbox).
Using plain span tags instead of comments would make things easier, but either way, I would suggest not using regular expressions for this. There can be border cases that may lead to undesired results.
If you stick with comment tags, I would iterate over the child nodes and then make the replacement, like so:
$("#fname").on("input", function () {
var thisval = $(this).val(); //gets replacement text from a text box
var thistoken = "firstname";
var between = false;
$("#gentextCodeArea").contents().each(function () {
if (this.nodeType === 8 && this.nodeValue.trim() === thistoken) {
if (between) return false;
between = true;
} else if (between) {
this.nodeValue = thisval;
thisval = '';
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
New first name: <input id="fname">
<div id="gentextCodeArea">
<!--firstname-->Harrison<!--firstname-->
<!--lastname-->Ford<!--lastname-->
<span class="spacer"></span></div>
What went wrong in your code
By using text() you don't get the comment tags. To get those, you need to use html() instead
replace() does not mutate the variable given in the first argument, but returns the modified string. So you need to assign that back to currentTemplate
It would be better to use [^<]* instead of \w+ for matching the first name, as some first names have non-letters in them (hyphen, space, ...), and it may even be empty.
Here is the corrected version, but I insist that regular expressions are not the best solution for such a task:
$("#fname").on("input", function () {
var thisval = $(this).val(); //gets replacement text from a text box
var thistoken = "firstname";
currentTemplate = $("#gentextCodeArea").html(); //fetch the html
var tokenstring = "<!--" + thistoken + "-->"
var pattern = new RegExp(tokenstring + '[^<]*' + tokenstring,'i');
currentTemplate = currentTemplate.replace(pattern, tokenstring + thisval + tokenstring);
$("#gentextCodeArea").html(currentTemplate); //put the new text back
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
New first name: <input id="fname">
<div id="gentextCodeArea">
<!--firstname-->Harrison<!--firstname-->
<!--lastname-->Ford<!--lastname-->
<span class="spacer"></span></div>
here is a function which will generate an appropriate Regular expression:
function templatePattern(key) {
return new RegExp(`<!--${key}-->(.*?)<!--${key}-->`);
}
the (.*?) means "match as little as possible," so it will stop at the first instance of the closing tag.
Example:
'<!--firstname-->Harrison<!--firstname--> <!--lastname-->Ford<!--lastname-->'
.replace(templatePattern('firstname'), 'Bob')
.replace(templatePattern('lastname'), 'Johnson') // "Bob Johnson"
$(function(){
function onKeyUp(event)
{
if(event.which === 38) // if key press was the up key
{
$('.firstname_placeholder').text($(this).val());
}
}
$('#firstname_input').keyup(onKeyUp);
});
input[type=text]{width:200px}
<input id='firstname_input' type='text' placeholder='type in a name then press the up key'/>
<table>
<tr>
<td ><span class='firstname_placeholder'>Harrison</span> <span class='lastname_placeholder'>Ford</span> <span class="spacer"></span></td>
</tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Categories