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.
Related
The below script returns the following into my html:
"3.9 °C {alarm,unackedAlarm}"
I would like to remove the "{alarm,unackedAlarm}" section so it just shows the temperature value. I believe I need to use a substring to achieve this but I cannot work out where to place it?
Thanks
<script src="https://requirejs.org/docs/release/2.3.6/minified/require.js" ></script>
require(['baja!', 'dialogs'], function (baja, dialogs) {
var sub = new baja.Subscriber();
sub.attach('changed', function(prop) {
if(prop.getName() === 'value');
{
document.getElementById("oat").innerHTML = ( this.get(prop));
}
});
baja.Ord.make('station:|slot:/BajaScriptExamples/Components/Ramp/out/value').get({ subscriber: sub});
});
'''
I would suggest using the regex approach just in case the number of characters change.
function extract(text) {
const pattern = /^(.*) {.*}$/g;
const match = [...text.matchAll(pattern)];
if (match.length == 0 || match[0].length == 0) {
console.error("text does not match");
return;
}
return match[0][1];
}
console.log(extract("3.9 °C {alarm,unackedAlarm}"));
The main idea here is to catch any string that follows this pattern (.*) {.*} and return what is in contained between the parenthesis (group).
The requirement of extracting specific part of a string can be done easily by using the split() function of Javascript.
Here are working examples using split:
Example 1: Split the string at blank spaces and print the first two parts.
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var str = "3.9 °C {alarm,unackedAlarm}"
var result = str.split(" ")
document.getElementById("demo").innerHTML = (result[0] + " " + result[1])
</script>
</body>
</html>
Example 2: Split the string at '{' and print the first part.
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var str = "3.9 °C {alarm,unackedAlarm}"
var result = str.split("{")
document.getElementById("demo").innerHTML = (result[0].trim())
</script>
</body>
</html>
Output:
3.9 °C
More information:
https://www.w3schools.com/jsref/jsref_split.asp
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
Trying to turn..
#one #two #three
into
one, two, three
Almost got it working but it misses the first one..
Code..
<!DOCTYPE html>
<html>
<body>
<p>Click the button to replace " #" with ", " in the paragraph below:</p>
<p id="demo">#one #two #three</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var str = document.getElementById("demo").innerHTML;
var res = str.replace(/ #/g, ", ");
document.getElementById("demo").innerHTML = res;
}
</script>
</body>
</html>
https://www.w3schools.com/code/tryit.asp?filename=GALOV6REXR1C
You can use String#replace with a callback where the function can be used to distinguish the replace value
<!DOCTYPE html>
<html>
<body>
<p>Click the button to replace " #" with ", " in the paragraph below:</p>
<p id="demo">#one #two #three</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var str = document.getElementById("demo").innerHTML;
var res = str.replace(/^#|( #)/g, (_, m1) => m1 ? ", " : '');
document.getElementById("demo").innerHTML = res;
}
</script>
</body>
</html>
I'd .match substrings that have a # right before them, and then .join by commas:
const str = '#one #two #three';
const arr = str.match(/(?<=#)\S+/g);
const output = arr.join(', ');
console.log(output);
Without lookbehind, if the hashtags are separated by spaces, split by spaces, .map to remove the first hash character from each, then join:
const str = '#one #two #three';
const output = str
.split(' ')
.map(hashtag => hashtag.slice(1))
.join(', ');
console.log(output);
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');
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);
}