search text after one element and replace it in javascript - javascript

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

Related

Convert to lowercase, uppercase, and then split the string into its own lines

I am trying to get a better hang of doing this and have been playing around with strings. What I am trying to do is collect a user input as a string and manipulate it so that when I display the text, whatever they wrote would be first displayed in all lower case, then all uppercase, then all of the text divided into its own line.
So, the output would be like this if I enter: This is an example
this is an example
THIS IS AN EXAMPLE
This
is
an
example
I feel like this is supposed to be a lot easier than it looks, but I am trying to do an all lowercase so far, but cannot get that to work so far (as well as the other two parts). I think that if I get the lowercase right, I just repeat the same thing for uppercase and splitting it.
<button onclick="myFunction()">Try it</button>
<p id="test"></p>
<script>
function myFunction() {
var person = prompt("Please enter a phrase");
if (person != null) {
document.getElementById("test").innerHTML =
test.toLowerCase;
document.getElementById("test").innerHTML =
test.toUpperCase;
document.getElementById("test").innerHTML =
test.split("\n");
}
}
</script>
The above is what I am playing with so far, I get undefined when I click the button to test it. Can someone help me edit this?
functions are invoked using ()
your variable is person not test
you want to split on space not \n
you want to ADD to test innerHTML, not replace it each time
to get line breaks in HTML, use <br> tag
I've gone for code that assigns innerHTML once, as this is more performant than adding to it a bit at a time - of course, with such a simple example there's no perceived difference, however I thought I should mention why I chose to use this odd methodology
function myFunction() {
var person = prompt("Please enter a phrase");
if (person != null) {
document.getElementById("test").innerHTML = [
person.toLowerCase(),
person.toUpperCase(),
person.split(" ").join('<br>')
].join("<br>");
}
}
<button onclick="myFunction()">Try it</button>
<p id="test"></p>
You may want to split the string into words first and use join() function with <br /> tags to render them into multiple lines of words.
function myFunction() {
var person = prompt("Please enter a phrase");
if (person != null) {
document.getElementById("test").innerHTML +=
person.toLowerCase() + "<br />";
document.getElementById("test").innerHTML +=
person.toUpperCase() + "<br />";
document.getElementById("test").innerHTML +=
person.split(' ').join('<br />');
}
}

How to insert a space before the every sentence in JavaScript?

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 to highlight dynamic words from response for different input string javascript, jquery, regex

[blog]: https://jsfiddle.net/kb413ae8/ "click here" for working fiddle
Kids Markers & Crayons is a response string for which highlighting of text should append, based on input we pass in searchQuery variable in code.
if Markers is provided as searchQuery input, Markers should be highlighted, which is currently working fine in above fiddle link.
if space is provided after word markers and pass has a searchQuery input in code, Kids 'b tag with class='boldTxt'>Markers & Crayons is appended. which is weird. Happens same for all word with space.
Highlight of text/word should happen if first character in searchQuery input matches with first character of word in response. does not matter where the word is. Thanks
var data = {"ResultSet":{"result":[
{"rank":"999999","term":"Kids Markers & Crayons"},
{"rank":"999999","term":"Crayola Fine Line Markers"},
{"rank":"999999","term":"Crayola Super Tips Washable Markers"},
{"rank":"999999","term":"Crayola Washable Markers Broad Line Classic"},
{"rank":"999999","term":"Post-it Assorted Page Markers"},
{"rank":"999999","term":"Crayola Markers Broad Line Classic"},
{"rank":"999999","term":"Crayola Crayons"},
{"rank":"999999","term":"Crayola Washable Markers Classic Colors"},
{"rank":"999999","term":"Crayola Washable Crayons Large"}]
,"totalResultsAvailable":"32","totalResultsReturned":11}};
for(i=0; i<9; i++) {
var result = data.ResultSet.result[i].term;
//console.log('result: ' + result);
var searchQuery = 'Markers ';
/*searchQuery inputs
searchQuery = 'c'; o/p: c should be highlighted at beginning of word, In classic 'c' is highlighting twice which should not be highlighted at end or in mid of word.
searchQuery = 'markers '; o/p: <b> tag is added which has to be removed.
searchQuery = 'markers & c '; o/p: <b> tag is added which has to be removed.
searchQuery = 'ola'; o/p: ola should be highlighted at beginning of word, In Crayola 'ola' is highlighting, which should not be highlighted at end or in mid of word.
*/
var searchResult = result;
words = searchQuery.split(' ');
$.each(words, function() {
var word = this.trim();
var regex = new RegExp('(' + word + ')(?!>|b>)', 'gi');
searchResult = searchResult.replace(regex, "<b class='boldTxt'>$1</b>");
});
console.log(searchResult);
$('#wag-typeaheadlists').append('<li><a>' + searchResult + '</a></li>')
}
.boldTxt {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<ul id="wag-typeaheadlists">
</ul>
In your fiddle try adding the following line after you split the searchQuery.
words = words.filter(function(word){ return word != "" });
Hope it solves your problem!

How do I find words starting with a specific letter?

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);

Skill the tag between <> using regex in JS/jquery

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"

Categories