replace multiple words using javascript? - javascript

I am using the following code to replace one word by an empty space in an input field.
however, I want to be able to replace multiple words with empty space.
basically I need to create a word filter so the users can't type certain words.
HTML CODE
<input type="text" id="demo" name="demo" onkeyup="myFunction()" onkeydown="myFunction()" />
Javascript code:
<script>
function myFunction() {
var words = "badword1";
var str = document.getElementById("demo").value;
var res = str.replace(words, " ");
document.getElementById("demo").value = res;
}
</script>
I've tried something like this:
<script>
function myFunction() {
var words = "badword1 || badword2 || bad word3";
var str = document.getElementById("demo").value;
var res = str.replace(words, " ");
document.getElementById("demo").value = res;
alert('that word is not allowed!');
}
</script>
but this doesn't work.
first, it doesn't replace any given badword(s) with empty space and second it fires the aler(); message as soon as I type the first letter in the input field!
could someone please help me out with this?

something like this takes the array of bad words... loops through them creates a global regex that then is used to replace it... compares the original and resulting string if they changed put alert.
var badwords = ['badword1','badword2','badword3']; //array of badwords
function myFunction() {
var str = document.getElementById("demo").value;
var res = str;
for (var i = badwords.length - 1; i >= 0; i--) {
var badword = badwords[i];
badWordRegex = new RegExp(badword, 'g');
res=res.replace(badWordRegex, " ");
};
document.getElementById("demo").value = res;
if (str !== res){
alert('that word is not allowed!');
}
}

Use regex:
var words = new RegExp("badword1|badword|bad word3", g);
ACtually you shouldn't trust client-side code...

Related

I need help getting a number from a <p> element with javascript

I am new in JavaScript. I have 3 numbers with 10 digits in a <p> tag, and I would like to select and convert them to a link. I was able to get the numbers and convert them to link, but I am getting all 3 numbers at the same time as one link, it would be great if I can get some help, Thank you
Here is my code:
<p>
What 0123456789 exactly is this Worker thread module, 9876543210 and why do we need it? 9768352461 In this post, we will talk about the historical reasons concurrency is implemented in JavaScript and Node.js, the problems we might find, current solutions, and the future of parallel processing with Worker threads.
</p>
<script>
function myFunction() {
var str = document.querySelector("p").innerHTML;
var link = 'https://www.google.com/search?q='+text;
var rgx = /\d{10}/g;
var text = str.match(rgx);
var res = str.replace(rgx, '"'+text+'"');
document.querySelector("p").innerHTML = res;
}
myFunction();
</script>
You can capture certain expressions in regex. Then you can get value from that group by using $ and a group number. There's only one group so in this case there'll be $1;
function myFunction() {
var str = document.querySelector("p").innerHTML;
var link = "https://www.google.com/search?q=$1";
var rgx = /(\d{10})/g; // () wraps an expression in a group
var text = str.match(rgx);
var res = str.replace(rgx, '$1');
document.querySelector("p").innerHTML = res;
}
More about capturing groups: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Groups_and_Ranges
Edit: I found even a simpler way - if you want to refer to the whole expression you don't need to create a group. To insert matched value you can use $&:
function myFunction() {
var str = document.querySelector("p").innerHTML;
var link = "https://www.google.com/search?q=$&";
var rgx = /\d{10}/g;
var text = str.match(rgx);
var res = str.replace(rgx, '$&');
document.querySelector("p").innerHTML = res;
}
str.match(rgx);
returns an array of matching strings. If you want to use only on item of the array, you can reference to the index (like text[0]) or you can i.e. loop over the array with text.forEach
or you can map over it and generate links like this:
let links = text.map((string) => { return `www.yourlink.com/${string}`})
in your replace statement use text instead of rgx
var res = str.replace(text, '"'+text+'"');
that way you only replace the instance of the matched text instead of all the rgx matches
EDIT
this should do it
function myFunction() {
var str = document.querySelector("p").innerHTML;
var rgx = /\d{10}/g;
var text = str.match(rgx);
for (i=0; i<text.length; i++) {
var link = 'https://www.google.com/search?q='+text[i];
str = str.replace(text[i], '"'+text[i]+'"');
}
document.querySelector("p").innerHTML = str;
}
myFunction();

Check if the string contains an entire word from an array of words (jquery, javascript)

I'm working on importing a word filter into a text input and I want to check if there is a match between a entire bad word that is in a array of words and a word that is inside a string, I will give an example of this...
List of bad words:
var bad_words = ['bad1', 'bad2', 'bad3'];
String with the value of text input:
var check_text = document.getElementById("text").value;
Lets say I have this word in my string (In this example I expect a false answer):
Here is bad2222
Lets say I have this word in my string (In this example I expect a true answer):
Here is bad2
After a slight correction to the code,
This is the code that solved this problem for me..Thx to ritaj
<script type="text/javascript">
function check_val() {
var bad_words = ['bad1', 'bad2', 'bad3'];
var check_text = document.getElementById("text").value;
var error = 0;
if (check_text.split(' ').some(part => bad_words.includes(part))) {
error = error + 1;
}
if (error > 0) {
document.getElementById("bad_notice").innerHTML = "WARNING: Some Bad Words In Your Text";
}
else {
document.getElementById("bad_notice").innerHTML = "";
}
}
</script>
<div id="wrapper">
<textarea id="text" onKeyUp="check_val()" placeholder="Write Some Text Having Words 'bad1', 'bad2', 'bad3'"></textarea>
<p id="bad_notice"></p>
</div>
you can use the reverse technique to check it.
var bad_words = ['bad1', 'bad2', 'bad3'];
const check_text = 'Here is bad222';
const found = bad_words.find(word => check_text.split(' ').find(s=>s===word));
if(found){
console.log("True")
}else{
console.log("False")
}

Regular expression not capturing multiple characters [duplicate]

I have a string in JavaScript (e.g., #box2), and I just want the 2 from it.
I tried:
var thestring = $(this).attr('href');
var thenum = thestring.replace(/(^.+)(\w\d+\w)(.+$)/i, '$2');
alert(thenum);
It still returns #box2 in the alert. How can I get it to work?
It needs to accommodate for any length number attached on the end.
For this specific example,
var thenum = thestring.replace(/^\D+/g, ''); // Replace all leading non-digits with nothing
In the general case:
thenum = "foo3bar5".match(/\d+/)[0] // "3"
Here's a bonus: regex generator.
function getre(str, num) {
if(str === num)
return 'nice try';
var res = [/^\D+/g,/\D+$/g,/^\D+|\D+$/g,/\D+/g,/\D.*/g, /.*\D/g,/^\D+|\D.*$/g,/.*\D(?=\d)|\D+$/g];
for(var i = 0; i < res.length; i++)
if(str.replace(res[i], '') === num)
return 'num = str.replace(/' + res[i].source + '/g, "")';
return 'no idea';
};
function update() {
$ = function(x) { return document.getElementById(x) };
var re = getre($('str').value, $('num').value);
$('re').innerHTML = 'Numex speaks: <code>' + re + '</code>';
}
<p>Hi, I'm Numex, the Number Extractor Oracle.
<p>What is your string? <input id="str" value="42abc"></p>
<p>What number do you want to extract? <input id="num" value="42"></p>
<p><button onclick="update()">Insert Coin</button></p>
<p id="re"></p>
You should try the following:
var txt = "#div-name-1234-characteristic:561613213213";
var numb = txt.match(/\d/g);
numb = numb.join("");
alert (numb);​
Result
1234561613213213
I think this regular expression will serve your purpose:
var num = txt.replace(/[^0-9]/g, '');
Where txt is your string.
It basically rips off anything that is not a digit.
I think you can achieve the same thing by using this as well:
var num = txt.replace(/\D/g, '');
Try the following: string.replace(/[^0-9]/g, ''); This will delete all non-digit characters, leaving only digits in the string
function retnum(str) {
var num = str.replace(/[^0-9]/g, '');
return parseInt(num,10);
}
console.log('abca12bc45qw'.replace(/[^0-9]/g, ''));
console.log('#box2'.replace(/[^0-9]/g, ''));
Using the match function.
var thenum = "0a1bbb2".match(/\d+$/)[0];
console.log(thenum);
And this is a snippet which extracts prices with currency and formatting:
var price = "£1,739.12";
parseFloat(price.replace(/[^\d\.]*/g, '')); // 1739.12
I tried all the combinations cited in the previous answer with this code and got it working. It was the only one that worked on that string → (12) 3456-7890
var str = "(12) 3456-7890";
str.replace(/\D+/g, '');
Result: "1234567890"
Obs: I know that a string like that will not be on the attribute, but whatever, the solution is better, because it’s more complete.
You may use the great parseInt() method.
It will convert the leading digits to a number:
parseInt("-10px");
// Will give you -10
You can extract numbers from a string using a regex expression:
let string = "xxfdx25y93.34xxd73";
let res = string.replace(/\D/g, "");
console.log(res);
Output: 25933473
Wrap it into a vanilla JavaScript function:
function onlyNumbers(text){
return text.replace(/\D/g, "");
}
For a string such as #box2, this should work:
var thenum = thestring.replace(/^.*?(\d+).*/,'$1');
jsFiddle:
http://jsfiddle.net/dmeku/
function justNumbers(string)
{
var numsStr = string.replace(/[^0-9]/g, '');
return parseInt(numsStr);
}
console.log(justNumbers('abcdefg12hijklmnop'));
You can do a function like this
function justNumbers(string)
{
var numsStr = string.replace(/[^0-9]/g, '');
return parseInt(numsStr);
}
Remember: if the number has a zero in front of it, the int won’t have it
If you want to parse a number from a price like $6,694.20, it can be done this way:
parseFloat('$6,694.20'.replace(/^\D|,+/g, ''))
Or via a function:
function parsePrice(value) {
return parseFloat(value.replace(/^\D|,+/g, ''))
}
parsePrice('$6,694.20') // 6694.2
To return an int from the string, you can do the following code. It removes all not number characters and returns an integer.
Number("strin[g]3".replace(/\D+/g, ""))
You can use a regular expression.
var txt="some text 2";
var numb = txt.match(/\d/g);
alert (numb);
That will alert 2.
let str = "Total Work Duration: 189.56 Hrs.Present: 23.5 Absent: 2";
/* The provided regex globally matches the character
"." and a digit from the string */
let numArr = str.match(/[\d\.]+/g)
/* It returns an array [189.56, ., 23.5, 2], and
uses the filter function to remove the '.' */
numArr = numArr.filter(n => n != '.')
console.log(numArr)
If someone need to preserve dots in extracted numbers:
var some = '65,87 EUR';
var number = some.replace(",",".").replace(/[^0-9&.]/g,'');
console.log(number); // returns 65.87
You can use Underscore.js' string library as follows:
var common = "#box"
var href = "#box1"
_(href).strRight(common)
The result will be: 1
See: Underscore.string
Demo:
http://jsfiddle.net/abdennour/Vyqtt/
HTML code:
<p>
<a href="#box1" >img1</a>
<a href="#box2" >img2</a>
<a href="#box3" >img3</a>
<a href="#box4" >img4</a>
</p>
<div style="font-size:30px"></div>
JavaScript code:
var comm = "#box"
$('a').click(function() {
$('div').html(_($(this).attr('href')).strRight(comm))})
If you have a suffix as follows:
href="box1az"
You can use the following demo:
http://jsfiddle.net/abdennour/Vyqtt/1/
function retrieveNumber(all, prefix, suffix) {
var left = _(all).strRight(prefix);
return _(left).strLeft(suffix);
}
Here's a solution that checks for no data:
var someStr = 'abc'; // Add 123 to string to see the inverse
var thenum = someStr.match(/\d+/);
if (thenum != null)
{
console.log(thenum[0]);
}
else
{
console.log('Not a number');
}
var elValue = "-12,erer3 4,-990.234sdsd";
var isNegetive = false;
if(elValue.indexOf("-") == 0)
isNegetive = true;
elValue = elValue.replace( /[^\d\.]*/g, '');
elValue = isNaN(Number(elValue)) ? 0 : Number(elValue);
if(isNegetive)
elValue = 0 - elValue;
alert(elValue); // -1234990.234
With regular expressions, how to get numbers from a string, for example:
String myString = "my 2 first gifts were made by my 4 brothers";
myString = myString.replaceAll("\\D+", "");
System.out.println("myString: " + myString);
The result of myString is "24".
You can see an example of this running code at http://ideone.com/iOCf5G.
Use this one-line code to get the first number in a string without getting errors:
var myInt = parseInt(myString.replace(/^[^0-9]+/, ''), 10);
Please check the below JavaScript code. There you can get only a number.
var txt = "abc1234char5678#!9";
var str = txt.match(/\d+/g, "") + '';
var s = str.split(',').join('');
alert(Number(s));
Output: 1234567789
You need to add "(/\d+/g)" which will remove all non-number text, but it will still be a string at this point. If you create a variable and "parseInt" through the match, you can set the new variables to the array values. Here is an example of how I got it to work:
var color = $( this ).css( "background-color" );
var r = parseInt(color.match(/\d+/g)[0]);
var g = parseInt(color.match(/\d+/g)[1]);
var b = parseInt(color.match(/\d+/g)[2]);
This answer will cover most of the scenarios. I came across this situation when a user tried to copy paste the phone number.
$('#help_number').keyup(function() {
$(this).val().match(/\d+/g).join("")
});
Explanation:
str = "34%^gd 5-67 6-6ds"
str.match(/\d+/g)
It will give an array of strings as output:
["34", "56766"]
 
str.match(/\d+/g).join("")
join() will convert and concatenate that array data into a single string.
Output:
"3456766"
In my example, I needed the output as 209-356-6788, so I used replace():
$('#help_number').keyup(function() {
$(this).val($(this).val().match(/\d+/g).join("").replace(/(\d{3})\-?(\d{3})\-?(\d{4})/, '$1-$2-$3'))
});
Written without a regular expression:
// Without Regex
function extractNumber(string) {
let numArray = string.split('').map(item => {
if (typeof +item === 'number' && !isNaN(+item))
return +item
})
return +numArray.join('')
}
extractNumber('#1200milion$') // 1200
In one of my projects I had to take a rating value from a string. This is what I used:
let text = '#xbox2'
let num = text.trim().
split('').
map(num => Number(num)).
filter(x => Number.isInteger(x))
Use:
changeStrangeDate(dateString: string) {
var sum = 0;
var numbers = dateString.match(/\d+/g);
if (numbers.length > 1) {
numbers.forEach(element => {
sum += parseInt(element);
}
);
}
console.log(new Date(sum).toDateString());
return new Date(sum).toUTCString();
}
You can do it like that and then call a function where you need it, with a parameter.
this.changeStrangeDate('/Date(1551401820000-0100)/');

JavaScript - How to underline the first character of every word

Sentence: Mr Blue has a blue house and a blue car.
JavaScript Code:
`
function myFunction(){
var str = document.getElementById("sentence").innerHTML;
for(var i=0; i<str.length;i++){
if(i == 0 )
{
var res = str.replace(str.charAt(i+1), "<u>"+str.charAt(i+1)+"</u>");
document.getElementById("sentence").innerHTML = res;
}else if(str.charAt(i) == " ")
{
var res = str.replace(str.charAt(i+1), "<u>"+str.charAt(i+1)+"</u>");
document.getElementById("sentence").innerHTML = res;
}
}`
Problem: I am trying to underline the first character in every word of a paragraph when a button is pressed. With the code I have only the C from car is underlined. if anyone can see where I have gone wrong or if there is a better way of doing this problem.
Thanks
Your code is working partially correct. It works on every word of the string but is getting updated again with next word.
You can make it simple by using a regex.
str.replace(/([^\s]+)/g,function(str){
return "<u>"+str.charAt(0)+"</u>" + str.slice(1);
})
Explanation of the regex:
(: Capturing group start
[^: Negated set - Match anything which is not in the set.
\s: Matches any whitespace character (spaces)
]: set ends
): Capturing group ends
Looking at the syntax of the javascript replace function:
str.replace(regexp|substr, newSubstr|function)
function (replacement)
A function to be invoked to create the new substring to be used to
replace the matches to the given regexp or substr. The arguments
supplied to this function are match, submatch, offset and the
original string. (Source: MDN)
Edit: You are still not using the accepted solution in your answer properly. This is how your function will look now:
<script>
function myFunction() {
var str = document.getElementById("Sentence").innerHTML;
var result = str.replace(/([^\s]+)/g,function(str){
return "<u>"+str.charAt(0)+"</u>" + str.slice(1);
});
document.getElementById("Sentence").innerHTML = result;
}
</script>
and if you are comfortable with ES6:
<script>
function myFunction() {
const str = document.getElementById("Sentence").innerHTML;
const result = str.replace(/([^\s]+)/g, p1 => `<u>${p1.charAt(0)}</u>${p1.slice(1)}` );
document.getElementById("Sentence").innerHTML = result;
}
</script>
You store the mutation inside res, but you don't update str, so at the next iteration the previous changes get discarded. Instead just mutate str:
str = str.replace(str.charAt(i+1), "<u>"+str.charAt(i+1)+"</u>");
And then after the loop is done reflect it to the DOM once:
document.getElementById("sentence").innerHTML = str;
How i would solve that:
function underline(selector) {
const el = document.querySelectorAll(selector);
let result = "";
for(const word of el.innerHTML.split(" ")) {
result += `<u>${word[0]}</u>${word.substr(1)}`;
}
el.innerHtML = result;
}
underline("#sentence");
var str = document.getElementById("sentence").innerHTML;
var words = str.match(/\S*/g);
var words2 = [];
words.forEach(function(item, i, arr) {
if (item!="")
{
words2.push(item.replace(item.charAt(1), "<u>"+item.charAt(1)+"</a>"));
}
});
document.getElementById("sentence").innerHTML = words2.join(" ");
Thanks guys for the help, greatly appreciated.
Full Solutions:
<!DOCTYPE html>
<html>
<body>
<p id="Sentence">Mr Blue has a blue house and a blue car.</p>
<button onclick="myFunction()">Click</button>
<script>
function myFunction() {
var str = document.getElementById("Sentence").innerHTML;
var res = str.replace(/([^\s]+)/g,function(str){
return "<u>"+str.charAt(0)+"</u>" + str.slice(1);
});
document.getElementById("Sentence").innerHTML = res;
}
</script>
</body>
</html>

Split sentence by space mixed up my index

I'm facing some problem while trying to send text to some spelling API.
The API return the corrections based on the words index, for example:
sentence:
"hello hoow are youu"
So the API index the words by numbers like that and return the correction based on that index:
0 1 2 3
hello hoow are youu
API Response that tell me which words to correct:
1: how
3: you
On the code I using split command to break the sentence into words array so I will be able to replace the misspelled words by their index.
string.split(" ");
My problem is that the API trim multiple spaces between words into one space, and by doing that the API words index not match my index. (I would like to preserve the spaces on the final output)
Example of the problem, sentence with 4 spaces between words:
Hello howw are youu?
0 1 2 3 4 5 6 7
hello hoow are youu
I thought about looping the words array and determine if the element is word or space and then create something new array like that:
indexed_words[0] = hello
indexed_words[0_1] = space
indexed_words[0_2] = space
indexed_words[0_3] = space
indexed_words[0_4] = space
indexed_words[0_5] = space
indexed_words[0_6] = space
indexed_words[0_7] = space
indexed_words[1] = how
indexed_words[2] = are
indexed_words[3] = you?
That way I could replace the misspelled words easily and than rebuild the sentence back with join command but the problem but the problem that I cannot use non-numeric indexes (its mixed up the order of the array)
Any idea how I can keep the formatting (spaces) but still correct the words?
Thanks
in that case you have very simple solution:L
$(document).ready(function(){
var OriginalSentence="howw are you?"
var ModifiedSentence="";
var splitstring=OriginalSentence.split(' ')
$.each(splitstring,function(i,v){
if(v!="")
{
//pass this word to your api and appedn it to sentance
ModifiedSentence+=APIRETURNVALUE//api return corrected value;
}
else{
ModifiedSentence+=v;
}
});
alert(ModifiedSentence);
});
Please review this one:
For string manipulation like this, I would highly recommend you to use Regex
Use online regex editor for faster try and error like here https://regex101.com/.
here I use /\w+/g to match every words if you want to ignore 1 or two words we can use /\w{2,}/g or something like that.
var str = "Hello howw are youu?";
var re = /\w+/g
var words = str.match(re);
console.log("Returning valus")
words.forEach(function(word, index) {
console.log(index + " -> " + word);
})
Correction
Just realize that you need to keep spacing as it is, please try this one:
I used your approach to change all to space. create array for its modified version then send to your API (I dunno that part). Then get returned data from API, reconvert it back to its original formating string.
var ori = `asdkhaskd asdkjaskdjaksjd askdjaksdjalsd a ksjdhaksjdhasd asdjkhaskdas`;
function replaceMeArr(str, match, replace) {
var s = str,
reg = match || /\s/g,
rep = replace || ` space `;
return s.replace(reg, rep).split(/\s/g);
}
function replaceMeStr(arr, match, replace) {
var a = arr.join(" "),
reg = match || /\sspace\s/g,
rep = replace || " ";
return a.replace(reg, rep);
}
console.log(`ori1: ${ori}`);
//can use it like this
var modified = replaceMeArr(ori);
console.log(`modi: ${modified.join(' ')}`);
//put it back
var original = replaceMeStr(modified);
console.log(`ori2: ${original}`);
Updated
var str = "Hello howw are youu?";
var words = str.split(" ");
// Getting an array without spaces/empty values
// send it to your API call
var requestArray = words.filter(function(word){
if (word) {
return word;
}
});
console.log("\nAPI Response that tell me which words to correct:");
console.log("6: how\n8: you");
var response = {
"1": "how",
"3": "you"
}
//As you have corrected words index, Replace those words in your "requestArray"
for (var key in response) {
requestArray[key] = response[key];
}
//now we have array of non-empty & correct spelled words. we need to put back empty (space's) value back in between this array
var count = 0;
words.forEach(function(word, index){
if (word) {
words[index] = requestArray[count];
count++;
}
})
console.log(words);
Correct me, if i was wrong.
Hope this helps :)
Try this JSFiddle
, Happy coding :)
//
// ReplaceMisspelledWords
//
// Created by Hilal Baig on 21/11/16.
// Copyright © 2016 Baigapps. All rights reserved.
//
var preservedArray = new Array();
var splitArray = new Array();
/*Word Object to preserve my misspeled words indexes*/
function preservedObject(pIndex, nIndex, title) {
this.originalIndex = pIndex;
this.apiIndex = nIndex;
this.title = title;
}
/*Preserving misspeled words indexes in preservedArray*/
function savePreserveIndexes(str) {
splitArray = str.split(" ");
//console.log(splitArray);
var x = 0;
for (var i = 0; i < splitArray.length; i++) {
if (splitArray[i].length > 0) {
var word = new preservedObject(i, x, splitArray[i]);
preservedArray.push(word);
x++;
}
}
};
function replaceMisspelled(resp) {
for (var key in resp) {
for (var i = 0; i < preservedArray.length; i++) {
wObj = preservedArray[i];
if (wObj.apiIndex == key) {
wObj.title = resp[key];
splitArray[wObj.originalIndex] = resp[key];
}
}
}
//console.log(preservedArray);
return correctedSentence = splitArray.join(" ");
}
/*Your input string to be corrected*/
str = "Hello howw are youu";
console.log(str);
savePreserveIndexes(str);
/*API Response in json of corrected words*/
var apiResponse = '{"1":"how","3":"you" }';
resp = JSON.parse(apiResponse);
//console.log(resp);
/*Replace misspelled words by corrected*/
console.log(replaceMisspelled(resp)); //Your solution

Categories

Resources