I want to find words which start with a specific letter in a string using the following code. The specific letter would be supplied by the user in a text box.
This is what I have:
<!DOCTYPE html>
<html>
<body>
<input id="srch" type="text" />
<button onClick=searchword()>Search</button>
<p id="wrd" > hallo, this is a test john doe .
Another tea house pole.
</p>
</body>
<script>
function searchword() {
var s = document.getElementById("wrd").innerHTML;
var p= document.getElementById("srch").value;
var regx = new RegExp("(?:^|\W)" + p + "(\w+)(?!\w)","gi");
var re = regx, match, matches = [];
while (match = re.exec(s)) {
matches.push(match[0]);
}
alert(matches);
}
</script>
</html>
You can use word boundaries \b, the following example shows how to match every word starting with t
var string ="hallo, this is a test john doe .Another tea house pole. Hey Tom."
result = string.match(/(\bt\S+\b)/ig);
//result = string.match(/(\st\S+)/ig); // alternative
document.write(result);
var string ="hallo, this is a test john doe .Another tea house pole. Hey
Tom."
result = string.match(/(\ba\S+\b)/ig);
document.write(result);
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
My Input is:
hello world one
hello world two
hello world three
I have tried so far:
$('.insertSpace').click(function(event) {
var textareaInput=$('.textareaInput').val();
var myString = ' ' + textareaInput.split();
$('.textareaInput').val(myString);
//console.log(myString);
});
It is working for just first sentence.I want to insert space in every sentence. Where is the fault in my code?
Its output should look like this:
hello world one
hello world two
hello world three
You can create a simple regex if you use the m modifier (which matches on a multi-line basis)
function addSpaces() {
var textarea = document.querySelector('textarea');
textarea.value = textarea.value.replace(/^(.)/gm, ' $1');
}
<textarea id="text">
hello world one
hello world two
hello world three
</textarea>
<button onclick="addSpaces()">Add Spaces</button>
However, if you also want to normalize spaces you can swap out that regex for this:
.replace(/^(?!\n)(\s*)(.)/gm, ' $2');
which will remove tabs, or pre-existing spaces and only add 1 space no matter how many times you run that function. It will leave new lines alone.
var myString = textareaInput.split("\n").map(function(str){
return ' ' + str;
}).join("\n");
I think by "sentence" you mean line. If so, you can use replace with a regular expression to do that. Example:
var textareaInput = $('.textareaInput').val();
var myString = " " + textareaInput.replace(/(\r?\n)/g, "$1 ");
$('.textareaInput').val(myString);
Live copy:
$('.insertSpace').click(function(event) {
var textareaInput = $('.textareaInput').val();
var myString = " " + textareaInput.replace(/(\r?\n)/g, "$1 ");
$('.textareaInput').val(myString);
});
<textarea class="textareaInput" cols="20" rows="5">
hello world one
hello world two
hello world three
</textarea>
<input type="button" class="insertSpace" value="Insert Space">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
If the desired outcome is to move/indent the text to the right you can just use padding:
.indent {
/* Indent with as much you as like to */
padding-left: 1rem;
}
<textarea class="indent" cols="20" rows="5">
Some text
Hello world
Winter's coming
</textarea>
How I do search one string and replace it with ""?
Example:
<div id="test">
<span>test</span>
</div>
<script>
document.getElementById("test").innerHTML = ""
</script>
I want find document.getElementById("test").innerHTML = "" and replaced it with "".
Important: I'm using this code in other files of the website so just want remove this code after <div id="test">.
Thank You...
If you want to search and replace character from a string then use it.
javascript with regular expression
var str = "Mr Blue has a blue house and a blue car";
var res = str.replace(/blue/g, " ");
Output
Mr has a blue house and a blue car
But if you want to do it for recursive then use this:
javascript code
var str = "Mr Blue has a blue house and a blue car";
var res = str.replace(/blue/gi, "red");
output
Mr has a house and a car
For more details: visit
I am trying to write some code that will match words typed into a text input with words in div's with the class 'searchable' and highlights these words. What I have now works if one or more word matches and there are no words which don't match. For example, if the searchable div had the phrase: hello world and in the input was hello world it would highlight both. If the input had just hello, it would highlight that word. But if the input had hello mars, it would not highlight the word hello, because mars is not in the string. this jsFiddle demonstrates this. Any ideas much appreciated. Here is the code. Thank you.
javaScript:
if($('#search').val().length !== 0){
$('.searchable').each(function(){
var search_value = $("#search").val();
var search_regexp = new RegExp(search_value, "g");
$(this).html($(this).html().replace(search_regexp,"<span class ='highlight'>"+search_value+"</span>"));
});
}
html:
<input type = "text" id = "search" value = "hello mars">
<div class = "searchable">hello world</div>
Something like this:
// http://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex
String.prototype.pregQuote = function()
{
return this.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
};
var keyword = $("#search").val();
var searchRegex = new RegExp( '(' + keyword.pregQuote() + ')' , "ig" );
$('.searchable').each(function(){
var html = $(this).html();
html = html.replace( searchRegex , '<span class="highlight">$1</span>');
$(this).html( html );
});
Hello All Developers,
i need your help in one case so what my requirement is-
i am trying to find a String word in inner html using js like-
var index = lcBodyinnerhtml.indexOf(Searchword, 0);
so my problem is that if i am try to find a word suppose "all man " and in inner html it is
like
here in this world <i>all</i>man are
so it is not finding that word so i want that using regex or something it will skip the <> of html tag so that i 'll be able to find the exact word
Please suggest me any suitable example,thanks in advanced
You could do something like this
Html:
<div id="text">here in this world <i>all</i> man are all man</div>
Jquery / Javascript:
$(document).ready(function(){
var searchword = 'all man';
var text = $('#text').text();
var repl = '<span style="color:red">' + searchword + '</span>';
var rgxp = new RegExp(searchword, 'g');
text = text.replace(rgxp, repl);
$('#text').html(text);
});
Hope this helps!
1 minute of googling and I found this: http://css-tricks.com/snippets/javascript/strip-html-tags-in-javascript/
var StrippedString = OriginalString.replace(/(<([^>]+)>)/ig,"");
You can use the StrippedString to search for your Substring:
var OriginalString = "here in this world <i>all</i>man are"
var StrippedString = OriginalString.replace(/(<([^>]+)>)/ig,"");
// StrippedString = "here in this world allman are"