How can I write a pattern for a name which can only include letters separated by single spaces if required? If there are multiple names, then they must be separated with a single space.
For example,
"Jane Doe" and "Jane" are correct but, " Jane" or "Jane " or "Jane Doe" are all incorrect.
My pattern,
/^([A-za-z]+ ?[A-za-z]+){1}$/
If i've understand you correctly, try this:
/^[A-Za-z]+(\s[A-Za-z]+)?$/
Your regular expression is not checking the full capital letter range (A-z must be A-Z)
NOTE: This is on the assumption that your question contains a typo and that in fact " Jane Doe" or "Jane Doe " is incorrect.
var patt=new RegExp(/^([A-Za-z]+ ?[A-Za-z]+){1}$/);
document.write(patt.test(" Jane Doe") + '<br/>'); --false
document.write(patt.test("Jane Doe") + '<br/>'); --true
document.write(patt.test(" Jane") + '<br/>'); -- false
document.write(patt.test("Doe ") + '<br/>'); -- false
document.write(patt.test("Doe") + '<br/>'); -- true
See fiddle: http://jsfiddle.net/FEycT/4/
Related
I want to replace second space occurrence of the sentence with a br.
I have tried this but it is deleting the rest.
var title = "My Title Needs Brace".split(" ").slice(0, 2).join(" ");
That will do the trick:
"My Title Needs Brace"
.split(' ')
.reduce(function (str, part, i) {
return str + (i === 2 ? '<br/>' : ' ') + part
});
// "My Title<br/>Needs Brace"
Let's break it and see how it works:
First, we take the string and split it. we'll use " " as our separator
"My Title Needs Brace".split(' ')
// ["My", "Title", "Needs", "Brace"]
Second, we'll use reduce to combine the array back into one string
["My", "Title", "Needs", "Brace"]
.reduce(function (str, part) { return str + ' ' + part }, '');
// "My Title Needs Brace"
Why reduce and not join?
The advantage of reduce over join is that it allows us to use a function, which will give us a fine-grained control over how we join back each part of the string
Now, all that left is to replace the 2nd space with <br/>,
for that, we'll use the 3rd argument of the reduce function, which stands for the index, and ask:
is this the 3rd part? use <br/>
otherwise, use " "
"My Title Needs Brace"
.split(' ')
.reduce(function (str, part, i) {
return str + (i === 2 ? '<br/>' : ' ') + part
});
// "My Title<br/>Needs Brace"
Note that this is the index of the string "part", not the spaces between them so the index is 2, not 1.
More about:
split
reduce
join
Try the following:
var title = "My Title Needs Brace".split(" ");
title.forEach(function(item, i, title){
if(i==1)
title[i] += "<br/>";
else
title[i] += ' ';
})
console.log(title.join(''));
I want to replace second space occurrence of the sentence with a br.
The simple way to do that is to add "<br/>" to the second element.
Here is the Code.
$(document).ready(function(){
var title = "My Title Needs Brace".split(" ");
title[1] = title[1]+"<br/>";
var newstr = title.join(" ");
$("#textd").html(newstr);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="textd">
</div>
maybe that will help :
var title = "My Title Needs Brace".split(" ");
t1=title [0]; My
t2=title[1]; // Title
t3=title[2]; // Needs
t4=title[3]; // Brace
you can drew here anything :
var htmlString = '' + t1 +''+ t2 + '<br />' + t3 +''+ t4 + '';
$('Anywhere').append(htmlString);
You can do this without splitting the string:
var title = 'My Title Needs Brace'.replace(/( .*?) /, '$1<br>');
Here, String.replace takes a RegExp and a string as arguments. The regex matches everything from the first space up through the second space, keeping everything except the second space in a capturing group. The string replaces the entire match with the contents of the capturing group, followed by '<br>'. Since the capturing group doesn't include the second space, this effectively only replaces the second space.
end_address = 'joe place, 555 test street, sacramento, ca, usa 95814';
end_address = end_address.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
The final result of this is:
Joe Place, 555 Test Street, Sacramento, Ca, Usa 95814
but my desired output is:
Joe Place, 555 Test Street, Sacramento, CA, USA 95814
How can I match a string so that "CA" and "USA" are always uppercase like the desired output?
This will work:
end_address = 'jOe place, 555 test street, sacramento, ca, usa 95814'.toLowerCase();
end_address = end_address.replace(/\b(usa\b|ca\b|\w)/g, function(txt) { return txt.toUpperCase(); });
alert(end_address);
First, I lowercase it all, then apply the capitalization regex, /\b(usa\b|ca\b|\w)/g, which looks for the start of a word. It will match, then capitalize "usa", "ca" or the first character of the word.
Assuming the pattern will always be the same, you need to do a second pass at the string.
var result = end_address
.replace(/\w\S*/g, function(txt){
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
}).replace(/(\w{2}), (\w+) (\d{5}(-\d{4})?)$/, function(match, state, country, zip) {
return state.toUpperCase() + ", " + country.toUpperCase() + ", " + zip;
});
What I'd do is something like this:
address = address.replace(
/([a-z]{2}),\s*([a-z]{3})\s*(\d{5})$/i,
function(match, state, country, zip) {
return state.toUpperCase() + ", " + country.toUpperCase() + " " + zip;
})
It'll do the replacement in one pass, and will only touch the state/country (assuming those are at the end of the string).
See the regex work on Regex101
I'm trying to develop a function in javascript that get a phrase and processes each word, preserving whiteSpaces. It would be something like this:
properCase(' hi,everyone just testing') => ' Hi,Everyone Just Testing'
I tried a couple of regular expressions but I couldn't find the way to get just the words, apply a function, and replace them without touching the spaces.
I'm trying with
' hi,everyone just testing'.match(/([^\w]*(\w*)[^\w]*)?/g, 'x')
[" hi,", "everyone ", "just ", "testing", ""]
But I can't understand why are the spaces being captured. I just want to capture the (\w*) group. also tried with /(?:[^\w]*(\w*)[^\w]*)?/g and it's the same...
What about something like
' hi,everyone just testing'.replace(/\b[a-z]/g, function(letter) {
return letter.toUpperCase();
});
If you want to process each word, you can use
' hi,everyone just testing'.replace(/\w+/g, function(word) {
// do something with each word like
return word.toUpperCase();
});
When you use the global modifier (g), then the capture groups are basically ignored. The returned array will contain every match of the whole expression. It looks like you just want to match consecutive word characters, in which case \w+ suffices:
>>> ' hi,everyone just testing'.match(/\w+/g)
["hi", "everyone", "just", "testing"]
See here: jsfiddle
function capitaliseFirstLetter(match)
{
return match.charAt(0).toUpperCase() + match.slice(1);
}
var myRe = /\b(\w+)\b/g;
var result = "hi everyone, just testing".replace(myRe,capitaliseFirstLetter);
alert(result);
Matches each word an capitalizes.
I'm unclear about what you're really after. Why is your regex not working? Or how to get it to work? Here's a way to extract words and spaces in your sentence:
var str = ' hi,everyone just testing';
var words = str.split(/\b/); // [" ", "hi", ",", "everyone", " ", "just", " ", "testing"]
words = word.map(function properCase(word){
return word.substr(0,1).toUpperCase() + word.substr(1).toLowerCase();
});
var sentence = words.join(''); // back to original
Note: When doing any string manipulation, replace will be faster, but split/join allows for cleaner, more descriptive code.
I want to use match and a regular expression to split a string into an array.
Example:
var strdoc = '<p>noi dung</p>bài viết đúng.Đó thực sự là, cuối cùng';
var arrdocobj = strdoc.match(/(<.+?>)|(\s)|(\w+)(.+?)/g);
When I do console.log arrdocobj, it results in
["<p>", "noi ", "dung<", "p>", "bà", "i ", "viế", "t ", "ng.", " ", "thự", "c ", "sự", " ", "là", " ", "cuố", "i ", "cù", "ng"]
How can I split the string to an array like this
["<p>", "noi"," ", "dung", "<p>","bài"," ","viết"," ","đúng",".","Đó"," ","thực"," ","sự"," ","là", "," ," ","cuối"," ","cùng"]
You could maybe use something like that?
var strdoc = '<p>noi dung</p>tiêu đề bài viết đúng';
var arrdocobj = strdoc.match(/<[^>]+>|\S+?(?= |$|<)/g);
I was looking into using the \b with the unicode flag, but I guess it isn't available in JS, so I used (?= |$|<) to emulate the word boundary.
jsfiddle demo
EDIT: As per edit of question:
<[^>]+>|[^ .,!?:<]+(?=[ .,!?:<]|$)|.
might do the trick.
jsfiddle demo.
I just added a few more punctuations and the |. for the remaining stuff to match.
I thing the following regex does what you are asking in your edit:
var strdoc = '<p>noi dung</p>bài viết đúng.Đó thực sự là, cuối cùng';
var arrdocobj = strdoc.match(/<[^>]+>|[\s]+|[^\s<]+/g);
Unfortunatly JavaScript does not support Unicode categories like \p{L} for any Unicode Letter
string=string.replace(RegExp(filter[a]+" | "+filter[a],"g"),filter[a])
For some reason, this isn't affecting both the filter followed by the space and the filter with a space in front. Assuming the filter is ",", it would take the second side and only replace " ," rather than " ," and ", ". The filter is user-specified, so I can't use a normal regular expression (which DOES work) such as string=string.replace(/, | ,/g,filter[a])
Can someone explain to me why it doesn't work and how to make it work?
It works for me:
s = 'abc, def,ghi ,klm'
a = ','
s = s.replace(RegExp(a + " | " + a, "g"), a)
"abc,def,ghi,klm"
Remember that you regular expression won't replace " , " with ",". You could try using this instead:
" ?" + filter[a] + " ?"