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
Related
I have a project where we have a compare the original code and code written by the user. The user can code and then on button click we have to compare the written code with original code.
I have both original and new code in string
originalHtml : <html><body style='color:white;background:purple;'></body></html>
newHtml : <html> <body style="background:purple;color:white;"> </body> . </html>
Here there are 3 things to keep in mind
1) White space (should not show the difference for white space)
2) ' and " (should not compare quotes, both are valid in HTML)
3) Attribute order (should show difference only for missing attribute, ignore attributes order)
Any suggestions or alternative solution will be appreciated.
I have created a code pen for you, this will solve your problem.
https://codepen.io/bearnithi/pen/KEPXrX
const textArea = document.getElementById('code');
const btn = document.getElementById('checkcode');
const result = document.getElementById('result');
let originalHTML = `<html><head>
<title>Hello </title>
</head><body>
<p class="hello"></p>
</body>
</html>`
btn.addEventListener('click', checkCode);
function checkCode() {
let newHTMLCode = textArea.value.replace(/\s/g,"");
let oldHTMLCode = originalHTML.replace(/\s/g,"");
if(newHTMLCode === oldHTMLCode) {
console.log(true);
result.innerHTML = 'TRUE';
} else {
console.log(false);
result.innerHTML = 'FALSE';
}
}
<textarea id="code">
</textarea>
</br>
<button id="checkcode">Check Code</button>
<p id="result"></p>
You can convert all of them to one uniform and compare them.
Example:
remove all space, tab (with one space)
replace all ' to "
sort attribute.
and some rule you defined
Example cheerio to get attribute:
var cheerio = require('cheerio');
var yourString = `<html><body attr2='hi' attr1='hello' style='color:white;background:purple;'></body></html>`;
var $ = cheerio.load(yourString);
var yourAttrs = $('body')[0].attribs;
var sorted = {};
Object.keys(yourAttrs).sort().forEach(function(key) {
sorted[key] = yourAttrs[key];
});
console.log(sorted);
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.
I'm developing a website and I need to break a word after "_".
For example, I have this "word":
test_test_test_test
And I want to break like this:
test_
test_
test_
test_
Is that possible?
Thanks.
I tried this, but didn't work:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var str = $('p').text();
var str_list = str.split("_");
for (var i = 0; i < str_list.length; i++) {
$('p').text(str_list[i] + "_");
}
});
</script>
</head>
<body>
<p>test_test_test_test</p>
<p>test2_test2_test2_test2</p>
</body>
</html>
'test_test_test_test'.match(/([a-z0-9]+_?)/gi)
the result is:
["test_", "test_", "test_", "test"]
You're looking for split.
var str = "test_test_test_test";
var str_list = str.split("_");
alert(str_list[0]);
If you want to print all of them then you need to iterate over the list.
for (var i = 0; i < str_list.length; i++) {
// I append the underscore to the end. Remove that bit if you don't want an underscore
alert(str_list[i] + "_");
}
var str ="test_test_test_test";
var parts=str.split('_');
parts.forEach(function(part){
alert(part+'_');
});
Here is another way to do it:
var words = word.replace(/_/g '_\0').split('\0');
The idea is to insert a marker after each _ and split on it. The marker should be a character that is not expected to appear in the actual data.
I am trying to write a quick program that counts the number of words in AngularJS. Basically a textarea in HTML and underneath it should display the number of words as the user inputs them.
So this is my HTML code:
<!doctype html>
<html ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"></script>
<script src="wordcount.js"></script>
</head>
<body>
<div ng-controller="wordCount">
<label>Copy and Paste your text:</label><br>
<textarea cols="80" rows="20" ng-model="mytext"></textarea>
<hr>
<span>{{wordCount()}} word(s)</span>
</div>
</body>
</html>
And here is my Javascript file called wordcount.js (to count the number of words in a given string):
function wordCount($scope) {
$scope.numberofwords = function(s) {
s = document.getElementById("mytext").value;
s = s.replace(/(^\s*)|(\s*$)/gi,"");
s = s.replace(/[ ]{2,}/gi," ");
s = s.replace(/\n /,"\n");
return s.split(' ').length;
}
}
I basically found the above on http://www.mediacollege.com/internet/javascript/text/count-words.html
So I have probably not fully understood how to use AngularJS (and the JS code is probably wrong too) to update the number of words instantly. Right now it doesn't show anything but "words".
Does anyone have an idea?
One of correct way is to use a $scope function:
<body ng-controller="WCController">
<h3>World count</h3>
<div>total words: <span ng-bind="countOf(myText)"></span></div>
<textarea ng-model="myText"></textarea>
</body>
and at the controller:
$scope.countOf = function(text) {
var s = text ? text.split(/\s+/) : 0; // it splits the text on space/tab/enter
return s ? s.length : '';
};
You can test this on plunker:
http://run.plnkr.co/Mk9BjXIUbs8hGoGm/
Solution
update a wordCount property when myText changes.
use simple regexp in a String.prototype.match call.
use this updated wordCount scope property in your template.
Code
Your watcher should look like something like that:
$scope.$watch('myText', function(text) {
// no text, no count
if(!text) {
$scope.wordCount = 0;
}
// search for matches and count them
else {
var matches = text.match(/[^\s\n\r]+/g);
$scope.wordCount = matches ? matches.length : 0;
}
});
Important note
Why computing the count in a watcher ?
To prevent this count from being computed on each digestion, the way it is when you use such a wordCount() method call in your template !
I wrote a regex tester in JS. However, it appears that for some regexes, I get multiple matches.
For example, if for the content hello, world, the regex hello.* is given, the it is reported to match hello, world. However, if the regex is now set to (hello|goodbye).* then the reported matches are hello, world and hello, whereas it should be hello, world only.
<!DOCTYPE html>
<html>
<head>
<title>Regex tester</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<script type="text/javascript">
function resetform() {
document.getElementById("results").innerHTML = "";
}
function escapetags(str) {
return (str.replace('&','&').replace('<', '<').replace('>', '>'));
}
function check() {
if (!document.form1.re.value) {
document.getElementById("results").innerHTML = '<p style="color:red"><b>Error: No regular expression specified</b></p>';
return;
}
if (!document.form1.str.value) {
document.getElementById("results").innerHTML = '<p style="color:red"><b>Error: No content specified</b></p>';
return;
}
var pattern,
modifiers = "";
if (document.form1.nocase.checked) {
modifiers = "i";
}
if (document.form1.global.checked) {
modifiers = modifiers + "g";
}
try {
if (modifiers) {
pattern = new RegExp(document.form1.re.value, modifiers);
} else {
pattern = new RegExp(document.form1.re.value);
}
} catch (excpt) {
document.getElementById("results").innerHTML = '<p style="color:red"><b>Error: Invalid regular expression</b></p>';
return;
}
var matches = pattern.exec(document.form1.str.value);
if (matches == null) {
document.getElementById("results").innerHTML = '<p><b>Regular expression did not match with content<b></p>';
} else {
document.getElementById("results").innerHTML = '<p><b>Regular expression matched with content</b></p><p>Matches:</p>';
for (var index = 0; index < matches.length; index++) {
document.getElementById("results").innerHTML += escapetags(matches[index]) + '<br>';
}
}
}
</script>
<h1>Regex tester</h1>
<form name="form1">
<p>Regex:</p>
<input type="text" name="re" size="65"><br>
<input type="checkbox" name="nocase">Case insensitive
<input type="checkbox" name="global">Global
<p>Content:</p>
<textarea name="str" rows="8" cols="65"></textarea><br><br>
<input type="button" value="Check" onclick="check();">
<input type="button" value="Reset" onclick="reset();resetform();">
</form>
<div id="results"></div>
</body>
</html>
Can anyone help me find the problem in my code?
Thanks in advance.
"(hello|goodbye). then the reported matches are hello, world and hello*"
No, the second "match" is just the result of your capturing group (what's between the parenthesis). Ignore it, or make the group non-capturing: (?:hello|goodbye)
The .exec() method of the JavaScript regex will return the entire matched string as the first element and then any captured groups as subsequent elements. When you use the regex:
(hello|goodbye).*
The brackets define a capture group, so your returned array will be
[0] = hello, world
[1] = hello
As Loamhoof suggest below, you can add ?: to make a group non-capturing if that is not desirable.
I think you want something like this,
var a = new RegExp("hello, world"); //or your string
var b = "hello, world";
if(a.test(b)){
//do your stuff
}
else{
//do your stuff
}
it will only match for the given pattern.