I need to take a user input, in this case as a search word. But when sending this input to an API, the string must not contain any spaces. I tried .trim but this seems to only remove any spaces before and/or after the string. Essentially, I need to force any amount of words other than one together, any thoughts on how this could be achieved would be greatly appreciated.
function getSearch(){
var welcomeMsg = document.getElementById('result');
var search_term = document.getElementById('floatingInput');
<input type="text" class="form-control" id="floatingInput">
<input type="button" value="click">
<label for="floatingInput">Song title / artist name</label>
You can use String.prototype.replace() for this, for example:
> 'foo bar'.replace(' ', '')
'foobar'
If there are expected to be many spaces, you can use a global regular expression:
> 'foo bar baz otherfoo'.replace(/ /g, '')
'foobarbazotherfoo'
Finally, if you still want to see the word boundaries as suggested by #JoeKincognito, you can update the second argument from an empty space '' to the separator of your choice, for example:
> 'foo bar baz otherfoo'.replace(/ /g, '-')
'foo-bar-baz-otherfoo'
This will allow you to separate the search terms later if necessary, and will allow you to differentiate between users searching for e.g., butter and fingers from users searching for butterfingers
string.replace() method supports regex expression:
xxx.replace(/\s+/g, '') //xxx is an example string.
\s: matches any whitespace symbol
Related
Hey I have a input where the user enters his social security number. To make the input more readable I want to insert a whitespace after the first 4 characters of the string. The social security number itself is 10 numbers long. So the result should looke like: 1234 567890. I only found solutions where a whitespace every 4 characters is inserted but no example which is similar to this. Has someone an idea how to solve this?
<input type="text" maxlength="10" #keyup="insertWhitespace()"/>
You can do this with the use of Regular Expression + HTML DOM Element addEventListener().
Reference Website For "Regular Expression": https://regexr.com/
With the help of a regular expression is a sequence of characters that specifies a search pattern in text or strings.
document.getElementById('example').addEventListener('input', function (e) {
e.target.value = e.target.value.replace(/[^\dA-Z]/g, '').replace(/(.{4})/, '$1 ').trim();
});
<input id="example" maxlength="11" name="example" />
I think you should make your max length to 11 because white space also counts and try it with the following code
const ssn = document.querySelector("selector");
ssn.addEventListener("keyup",(e) => {
if(e.target.value.length === 4){
ssn.value += " "
}
})
Here is the solution (Javascript) to your problem:
The code below reads the input value and remove alphabets and then replaces the digit value with the appropriate space character only once as expected after 4 digits.
function insertWhitespace() {
document.getElementById('myElement').value = document.getElementById('myElement').value.replace(/[^\dA-Z]/g, '').replace(/(.{4})/, '$1 ').trim()
}
<input id="myElement" maxlength="11" onkeyup="insertWhitespace()" />
I have a string of text with HTML line breaks. Some of the <br> immediately follow a number between two delimiters «...» and some do not.
Here's the string:
var str = ("«1»<br>«2»some text<br>«3»<br>«4»more text<br>«5»<br>«6»even more text<br>");
I’m looking for a conditional regex that’ll remove the number and delimiters (ex. «1») as well as the line break itself without removing all of the line breaks in the string.
So for instance, at the beginning of my example string, when the script encounters »<br> it’ll remove everything between and including the first « to the left, to »<br> (ex. «1»<br>). However it would not remove «2»some text<br>.
I’ve had some help removing the entire number/delimiters (ex. «1») using the following:
var regex = new RegExp(UsedKeys.join('|'), 'g');
var nextStr = str.replace(/«[^»]*»/g, " ");
I sure hope that makes sense.
Just to be super clear, when the string is rendered in a browser, I’d like to go from this…
«1»
«2»some text
«3»
«4»more text
«5»
«6»even more text
To this…
«2»some text
«4»more text
«6»even more text
Many thanks!
Maybe I'm missing a subtlety here, if so I apologize. But it seems that you can just replace with the regex: /«\d+»<br>/g. This will replace all occurrences of a number between « & » followed by <br>
var str = "«1»<br>«2»some text<br>«3»<br>«4»more text<br>«5»<br>«6»even more text<br>"
var newStr = str.replace(/«\d+»<br>/g, '')
console.log(newStr)
To match letters and digits you can use \w instead of \d
var str = "«a»<br>«b»some text<br>«hel»<br>«4»more text<br>«5»<br>«6»even more text<br>"
var newStr = str.replace(/«\w+?»<br>/g, '')
console.log(newStr)
This snippet assumes that the input within the brackets will always be a number but I think it solves the problem you're trying to solve.
const str = "«1»<br>«2»some text<br>«3»<br>«4»more text<br>«5»<br>«6»even more text<br>";
console.log(str.replace(/(«(\d+)»<br>)/g, ""));
/(«(\d+)»<br>)/g
«(\d+)» Will match any brackets containing 1 or more digits in a row
If you would prefer to match alphanumeric you could use «(\w+)» or for any characters including symbols you could use «([^»]+)»
<br> Will match a line break
//g Matches globally so that it can find every instance of the substring
Basically we are only removing the bracketed numbers if they are immediately followed by a line break.
I am a newbie in coding JS and hope someone can guide me to the right direction of my keyword system. Below are the requirements for keyword text field's behavior.
Only non-symbol character (includes letter, digit and other countries' languages) and space are allowed. If any symbols are entered, it should be replaced by '' / the input text will not display the symbols.
the hash (#) should be added instantly when the first non-symbol character of keyword is entered.
the keyword is separated by a space
Below are my codes:
function hashtag() {
str = document.getElementById('tagid').value;
tagged = str.replace(/#/g, '').replace(/([a-zA-Z0-9]+)/g, '#' + '$1');
document.getElementById('tagid').value = tagged;
}
Enter keyword:
<input type="text" name="tag" id="tagid" onkeypress="hashtag();" />
The problem are, the hash (#) can only be added when I entered the second non-symbol character / a space, but not the first one. And, there is no handling for symbols' input and no hash added before other countries languages.
Thanks in advance!
Here's a snippet that should work. My changes are:
Use onkeydown instead of onkeyup to trigger the function. onkeydown fires before the letter has been inserted into the text field and so the function doesn't see the key you just typed.
Use [^a-zA-Z0-9]/g as the regex. ^ means "anything but", so basically you're removing everything except the characters listed there. You could also use [^\w]/g but that would also allow the underscore which may or may not want.
Add an extra step to preappend the # because the above step removes it. (may seem wasteful but it's elegant and plenty fast enough)
function hashtag() {
//get the current contents of the text field
var str = document.getElementById('tagid').value;
//strip any non-word characters (will also strip hash symbol)
str = str.replace(/[^a-zA-Z0-9]/g, '');
//add the hash symbol back
str = '#' + str;
//update the text field
document.getElementById('tagid').value = str;
}
Enter keyword:
<input type="text" name="tag" id="tagid" onkeyup="hashtag();" />
For the first issue of the hash only being applied on the second press, you can use onkeyup="hashtag();" to execute the action after the keypress, once the text has been added to the input field and can then be evaluated.
Here is some documentation on JavaScript keypress events that may be helpful.
For removing symbols whilst still allowing foreign characters, I couldn't find anything great in pure js (PHP has ways to work around this which is interesting), so I've taken a different route of deleting all excluded characters (hopefully, if there's more please edit in to make more complete) and then "hash-tagging" everything else that isn't a space.
This would leave you with a function like this:
function hashtag() {
str = document.getElementById('tagid').value;
str = str.replace(/[-!$%^&*()_+|~=`{}\[\]:";'<>?,.##£\/]/g, '');
tagged = str.replace(/#/g, '').replace(/([^" "]+)/g, '#'+'$1');
document.getElementById('tagid').value = tagged;
}
Here's the complete code that you can run within the answer:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>HashTag</title>
<SCRIPT TYPE="TEXT/JAVASCRIPT">
function hashtag() {
str = document.getElementById('tagid').value;
str = str.replace(/[-!$%^&*()_+|~=`{}\[\]:";'<>?,.##£\/]/g, '');
tagged = str.replace(/#/g, '').replace(/([^" "]+)/g, '#'+'$1');
document.getElementById('tagid').value = tagged;
}
</script>
</head>
<body>
Enter keyword: <INPUT TYPE="text" NAME="tag" id="tagid" onkeyup="hashtag();"></input>
</body>
</html>
bind to onkeyup event
replace [a-zA-Z0-9]+ by \w+
for foreign symbols, you will have to add them one by one (I tried to put as many as I could find):
I added the i flag for your regex, you won't have to worry about uppercase letters like 'Â' as long as you have the lower case one
function hashtag() {
str = document.getElementById('tagid').value;
tagged = str.replace(/#/g, '').replace(/([\wâàãäéèêëîìôòõòùûüñ]+)/gi, '#'+'$1');
document.getElementById('tagid').value = tagged;
}
Enter keyword: <input TYPE="text" NAME="tag" id="tagid" onkeyup="hashtag();"/>
Edit :
not sure if you want to keep or remove special characters, here is a version were special chars are removed :
function hashtag() {
str = document.getElementById('tagid').value;
// remove things
str = str.replace(/[^\w ]/g, '');
tagged = str.replace(/(\w+)/gi, '#'+'$1');
document.getElementById('tagid').value = tagged;
}
Enter keyword: <input TYPE="text" NAME="tag" id="tagid" onkeyup="hashtag();"/>
I have a JS stirng like this
<div id="grouplogo_nav"><br> <ul><br> <li><a class="group_hlfppt" target="_blank" href="http://www.hlfppt.org/"> </a></li><br> </ul><br> </div>
I need to remove all <br> and $nbsp; that are only between > and <. I tried to write a regular expression, but didn't got it right. Does anybody have a solution.
EDIT :
Please note i want to remove only the tags b/w > and <
Avoid using regex on html!
Try creating a temporary div from the string, and using the DOM to remove any br tags from it. This is much more robust than parsing html with regex, which can be harmful to your health:
var tempDiv = document.createElement('div');
tempDiv.innerHTML = mystringwithBRin;
var nodes = tempDiv.childNodes;
for(var nodeId=nodes.length-1; nodeId >= 0; --nodeId) {
if(nodes[nodeId].tagName === 'br') {
tempDiv.removeChild(nodes[nodeId]);
}
}
var newStr = tempDiv.innerHTML;
Note that we iterate in reverse over the child nodes so that the node IDs remain valid after removing a given child node.
http://jsfiddle.net/fxfrt/
myString = myString.replace(/^( |<br>)+/, '');
... where /.../ denotes a regular expression, ^ denotes start of string, ($nbsp;|<br>) denotes " or <br>", and + denotes "one or more occurrence of the previous expression". And then simply replace that full match with an empty string.
s.replace(/(>)(?: |<br>)+(\s?<)/g,'$1$2');
Don't use this in production. See the answer from Phil H.
Edit: I try to explain it a bit and hope my english is good enough.
Basically we have two different kinds of parentheses here. The first pair and third pair () are normal parentheses. They are used to remember the characters that are matched by the enclosed pattern and group the characters together. For the second pair, we don't need to remember the characters for later use, so we disable the "remember" functionality by using the form (?:) and only group the characters to make the + work as expected. The + quantifier means "one or more occurrences", so or <br> must be there one or more times. The last part (\s?<) matches a whitespace character (\s), which can be missing or occur one time (?), followed by the characters <. $1 and $2 are kind of variables that are replaces by the remembered characters of the first and third parentheses.
MDN provides a nice table, which explains all the special characters.
You need to replace globally. Also don't forget that you can have the being closed . Try this:
myString = myString.replace(/( |<br>|<br \/>)/g, '');
This worked for me, please note for the multi lines
myString = myString.replace(/( |<br>|<br \/>)/gm, '');
myString = myString.replace(/^( |<br>)+/, '');
hope this helps
I am trying to read in a list of words separated by spaces from a textbox with Javascript. This will eventually be in a website.
Thank you.
This should pretty much do it:
<textarea id="foo">some text here</textarea>
<script>
var element = document.getElementById('foo');
var wordlist = element.value.split(' ');
// wordlist now contains 3 values: 'some', 'text' and 'here'
</script>
A more accurate way to do this is to use regular expressions to strip extra spaces first, and than use #Aron's method, otherwise, if you have something like "a b c d e" you will get an array with a lot of empty string elements, which I'm sure you don't want
Therefore, you should use:
<textarea id="foo">
this is some very bad
formatted text a
</textarea>
<script>
var str = document.getElementById('foo').value;
str = str.replace(/\s+/g, ' ').replace(/^\s+|\s$/g);
var words = str.split(' ');
// words will have exactly 7 items (the 7 words in the textarea)
</script>
The first .replace() function replaces all consecutive spaces with 1 space and the second one trims the whitespace from the start and the end of the string, making it ideal for word parsing :)
Instead of splitting by whitespaces, you can also try matching sequences of non-whitespace characters.
var words = document.getElementById('foo').value.match(/\S+/g);
Problems with the splitting method is that when there are leading or trailing whitespaces, you will get an empty element for them. For example, " hello world " would give you ["", "hello", "world", ""].
You may strip the whitespaces before and after the text, but there is another problem: When the string is empty. For example, splitting "" will give you [""].
Instead of finding what we don't want and split it, I think it is better to look for what we want.